/
svc.cpp
3219 lines (2779 loc) · 72.8 KB
/
svc.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: svc.cpp
* DESCRIPTION: Service manager functions
*
* 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): ______________________________________.
*
* 2002.02.15 Sean Leyne - Code Cleanup, removed obsolete "EPSON" define
* 2002.02.15 Sean Leyne - Code Cleanup, removed obsolete "IMP" port
*
* 2002.10.27 Sean Leyne - Completed removal of obsolete "DELTA" port
* 2002.10.27 Sean Leyne - Completed removal of obsolete "IMP" port
*
* 2002.10.29 Sean Leyne - Removed obsolete "Netware" port
*
* 2008 Alex Peshkoff - refactored services code for MT safe engine
*/
#include "firebird.h"
#include <stdio.h>
#include <string.h>
#include "../common/file_params.h"
#include <stdarg.h>
#include "../jrd/jrd.h"
#include "../jrd/svc.h"
#include "../jrd/constants.h"
#include "gen/iberror.h"
#include "../jrd/license.h"
#include "../jrd/err_proto.h"
#include "../yvalve/gds_proto.h"
#include "../jrd/inf_proto.h"
#include "../common/isc_proto.h"
#include "../jrd/jrd_proto.h"
#include "../jrd/mov_proto.h"
#include "../yvalve/why_proto.h"
#include "../jrd/jrd_proto.h"
#include "../common/classes/alloc.h"
#include "../common/classes/init.h"
#include "../common/classes/ClumpletWriter.h"
#include "../common/utils_proto.h"
#include "../common/db_alias.h"
#include "../jrd/scl.h"
#include "../common/msg_encode.h"
#include "../jrd/trace/TraceManager.h"
#include "../jrd/trace/TraceObjects.h"
#include "../jrd/EngineInterface.h"
#include "../jrd/Mapping.h"
#include "../common/classes/RefMutex.h"
#include "../common/os/os_utils.h"
#include "../common/classes/DbImplementation.h"
// The switches tables. Needed only for utilities that run as service, too.
#include "../common/classes/Switches.h"
#include "../alice/aliceswi.h"
#include "../burp/burpswi.h"
#include "../utilities/gsec/gsecswi.h"
#include "../utilities/gstat/dbaswi.h"
#include "../utilities/nbackup/nbkswi.h"
#include "../jrd/trace/traceswi.h"
#include "../jrd/val_proto.h"
// Service threads
#include "../burp/burp_proto.h"
#include "../alice/alice_proto.h"
int main_gstat(Firebird::UtilSvc* uSvc);
#include "../utilities/nbackup/nbk_proto.h"
#include "../utilities/gsec/gsec_proto.h"
#include "../jrd/trace/TraceService.h"
#include "../jrd/val_proto.h"
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#ifdef HAVE_SYS_WAIT_H
# include <sys/wait.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_VFORK_H
#include <vfork.h>
#endif
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#if !defined(WIN_NT)
# include <signal.h>
# include <sys/param.h>
# include <errno.h>
#else
# include <windows.h>
# include <io.h> // _open, _get_osfhandle
# include <stdlib.h>
#endif
#include <sys/stat.h>
#define statistics stat
using namespace Firebird;
const int SVC_user_dba = 2;
const int SVC_user_any = 1;
const int SVC_user_none = 0;
const int GET_LINE = 1;
const int GET_EOF = 2;
const int GET_BINARY = 4;
const int GET_ONCE = 8;
const char* const SPB_SEC_USERNAME = "isc_spb_sec_username";
namespace {
// Generic mutex to synchronize services
GlobalPtr<Mutex> globalServicesMutex;
// All that we need to shutdown service threads when shutdown in progress
typedef Array<Jrd::Service*> AllServices;
GlobalPtr<AllServices> allServices; // protected by globalServicesMutex
volatile bool svcShutdown = false;
class ThreadCollect
{
public:
ThreadCollect(MemoryPool& p)
: threads(p)
{ }
void join()
{
// join threads to be sure they are gone when shutdown is complete
// no need locking something cause this is expected to run when services are closing
waitFor(threads);
}
void add(Thread::Handle& h)
{
// put thread into completion wait queue when it finished running
MutexLockGuard g(threadsMutex, FB_FUNCTION);
threads.add(h);
}
void houseKeeping()
{
if (!threads.hasData())
return;
// join finished threads
AllThreads t;
{ // mutex scope
MutexLockGuard g(threadsMutex, FB_FUNCTION);
t.assign(threads);
threads.clear();
}
waitFor(t);
}
private:
typedef Array<Thread::Handle> AllThreads;
static void waitFor(AllThreads& thr)
{
while (thr.hasData())
{
Thread::Handle h(thr.pop());
Thread::waitForCompletion(h);
}
}
AllThreads threads;
Mutex threadsMutex;
};
GlobalPtr<ThreadCollect> threadCollect;
void spbVersionError()
{
ERR_post(Arg::Gds(isc_bad_spb_form) <<
Arg::Gds(isc_wrospbver));
}
} // anonymous namespace
using namespace Jrd;
namespace {
const serv_entry services[] =
{
{ isc_action_svc_backup, "Backup Database", BURP_main },
{ isc_action_svc_restore, "Restore Database", BURP_main },
{ isc_action_svc_repair, "Repair Database", ALICE_main },
{ isc_action_svc_add_user, "Add User", GSEC_main },
{ isc_action_svc_delete_user, "Delete User", GSEC_main },
{ isc_action_svc_modify_user, "Modify User", GSEC_main },
{ isc_action_svc_display_user, "Display User", GSEC_main },
{ isc_action_svc_properties, "Database Properties", ALICE_main },
{ isc_action_svc_db_stats, "Database Stats", main_gstat },
{ isc_action_svc_get_fb_log, "Get Log File", Service::readFbLog },
{ isc_action_svc_nbak, "Incremental Backup Database", NBACKUP_main },
{ isc_action_svc_nrest, "Incremental Restore Database", NBACKUP_main },
{ isc_action_svc_trace_start, "Start Trace Session", TRACE_main },
{ isc_action_svc_trace_stop, "Stop Trace Session", TRACE_main },
{ isc_action_svc_trace_suspend, "Suspend Trace Session", TRACE_main },
{ isc_action_svc_trace_resume, "Resume Trace Session", TRACE_main },
{ isc_action_svc_trace_list, "List Trace Sessions", TRACE_main },
{ isc_action_svc_set_mapping, "Set Domain Admins Mapping to RDB$ADMIN", GSEC_main },
{ isc_action_svc_drop_mapping, "Drop Domain Admins Mapping to RDB$ADMIN", GSEC_main },
{ isc_action_svc_display_user_adm, "Display User with Admin Info", GSEC_main },
{ isc_action_svc_validate, "Validate Database", VAL_service},
{ 0, NULL, NULL }
};
}
Service::Validate::Validate(Service* svc)
: sharedGuard(globalServicesMutex, FB_FUNCTION)
{
sharedGuard.enter();
if (!svc->locateInAllServices())
{
// Service is so old that it's even missing in allServices array
Arg::Gds(isc_bad_svc_handle).raise();
}
// Appears we have correct service object, may use it later to lock mutex
}
Service::SafeMutexLock::SafeMutexLock(Service* svc, const char* f)
: Validate(svc),
existenceMutex(svc->svc_existence),
from(f)
{
sharedGuard.leave();
}
bool Service::SafeMutexLock::lock()
{
existenceMutex->enter(from);
return existenceMutex->link;
}
Service::ExistenceGuard::ExistenceGuard(Service* svc, const char* from)
: SafeMutexLock(svc, from)
{
if (!lock())
{
// could not lock service
existenceMutex->leave();
Arg::Gds(isc_bad_svc_handle).raise();
}
}
Service::ExistenceGuard::~ExistenceGuard()
{
try
{
existenceMutex->leave();
}
catch (const Exception&)
{
DtorException::devHalt();
}
}
Service::UnlockGuard::UnlockGuard(Service* svc, const char* from)
: SafeMutexLock(svc, from), locked(false), doLock(false)
{
existenceMutex->leave();
doLock = true;
}
bool Service::UnlockGuard::enter()
{
if (doLock)
{
locked = lock();
doLock = false;
}
return locked;
}
Service::UnlockGuard::~UnlockGuard()
{
if (!enter())
{
// could not lock service
DtorException::devHalt();
}
}
void Service::getOptions(ClumpletReader& spb)
{
svc_spb_version = spb.getBufferTag();
for (spb.rewind(); !(spb.isEof()); spb.moveNext())
{
switch (spb.getClumpTag())
{
case isc_spb_user_name:
spb.getString(svc_username);
fb_utils::dpbItemUpper(svc_username);
break;
case isc_spb_sql_role_name:
spb.getString(svc_sql_role);
break;
case isc_spb_auth_block:
svc_auth_block.clear();
svc_auth_block.add(spb.getBytes(), spb.getClumpLength());
break;
case isc_spb_command_line:
spb.getString(svc_command_line);
break;
case isc_spb_expected_db:
spb.getPath(svc_expected_db);
break;
case isc_spb_address_path:
spb.getData(svc_address_path);
{
ClumpletReader address_stack(ClumpletReader::UnTagged,
spb.getBytes(), spb.getClumpLength());
while (!address_stack.isEof())
{
if (address_stack.getClumpTag() != isc_dpb_address)
{
address_stack.moveNext();
continue;
}
ClumpletReader address(ClumpletReader::UnTagged,
address_stack.getBytes(), address_stack.getClumpLength());
while (!address.isEof())
{
switch (address.getClumpTag())
{
case isc_dpb_addr_protocol:
address.getString(svc_network_protocol);
break;
case isc_dpb_addr_endpoint:
address.getString(svc_remote_address);
break;
default:
break;
}
address.moveNext();
}
break;
}
}
break;
case isc_spb_process_name:
spb.getString(svc_remote_process);
break;
case isc_spb_process_id:
svc_remote_pid = spb.getInt();
break;
case isc_spb_utf8_filename:
svc_utf8 = true;
break;
}
}
}
void Service::parseSwitches()
{
svc_parsed_sw = svc_switches;
svc_parsed_sw.trim();
argv.clear();
argv.push("service"); // why not use it for argv[0]
if (svc_parsed_sw.isEmpty())
{
return;
}
bool inStr = false;
for (FB_SIZE_T i = 0; i < svc_parsed_sw.length(); ++i)
{
switch (svc_parsed_sw[i])
{
case SVC_TRMNTR:
svc_parsed_sw.erase(i, 1);
if (inStr)
{
if (i < svc_parsed_sw.length() && svc_parsed_sw[i] != SVC_TRMNTR)
{
inStr = false;
--i;
}
}
else
{
inStr = true;
--i;
}
break;
case ' ':
if (!inStr)
{
svc_parsed_sw[i] = 0;
}
break;
}
}
argv.push(svc_parsed_sw.c_str());
for (const char* p = svc_parsed_sw.begin(); p < svc_parsed_sw.end(); ++p)
{
if (!*p)
{
argv.push(p + 1);
}
}
}
void Service::outputVerbose(const char* text)
{
if (!usvcDataMode)
{
ULONG len = static_cast<ULONG>(strlen(text));
enqueue(reinterpret_cast<const UCHAR*>(text), len);
}
}
void Service::outputError(const char* /*text*/)
{
fb_assert(false);
}
void Service::outputData(const void* data, FB_SIZE_T len)
{
fb_assert(usvcDataMode);
enqueue(reinterpret_cast<const UCHAR*>(data), len);
}
void Service::printf(bool err, const SCHAR* format, ...)
{
// Errors are returned from services as vectors
fb_assert(!err);
if (err || usvcDataMode)
{
return;
}
// Ensure that service is not detached.
if (svc_flags & SVC_detached)
{
return;
}
string buf;
va_list arglist;
va_start(arglist, format);
buf.vprintf(format, arglist);
va_end(arglist);
enqueue(reinterpret_cast<const UCHAR*>(buf.begin()), buf.length());
}
bool Service::isService()
{
return true;
}
void Service::started()
{
// ExistenceGuard guard(this, FB_FUNCTION);
// Not needed here - lock is taken by thread waiting for us
if (!(svc_flags & SVC_evnt_fired))
{
svc_flags |= SVC_evnt_fired;
svcStart.release();
}
}
void Service::putLine(char tag, const char* val)
{
const ULONG len = strlen(val) & 0xFFFF;
UCHAR buf[3];
buf[0] = tag;
buf[1] = len;
buf[2] = len >> 8;
enqueue(buf, sizeof buf);
enqueue(reinterpret_cast<const UCHAR*>(val), len);
}
void Service::putSLong(char tag, SLONG val)
{
UCHAR buf[5];
buf[0] = tag;
buf[1] = val;
buf[2] = val >> 8;
buf[3] = val >> 16;
buf[4] = val >> 24;
enqueue(buf, sizeof buf);
}
void Service::putSInt64(char tag, SINT64 val)
{
UCHAR buf[9];
buf[0] = tag;
buf[1] = val;
buf[2] = val >> 8;
buf[3] = val >> 16;
buf[4] = val >> 24;
buf[5] = val >> 32;
buf[6] = val >> 40;
buf[7] = val >> 48;
buf[8] = val >> 56;
enqueue(buf, sizeof buf);
}
void Service::putChar(char tag, char val)
{
UCHAR buf[2];
buf[0] = tag;
buf[1] = val;
enqueue(buf, sizeof buf);
}
void Service::putBytes(const UCHAR* bytes, FB_SIZE_T len)
{
enqueue(bytes, len);
}
void Service::setServiceStatus(const ISC_STATUS* status_vector)
{
if (checkForShutdown())
{
return;
}
Arg::StatusVector passed(status_vector);
ERR_post_nothrow(passed, &svc_status);
}
void Service::setServiceStatus(const USHORT facility, const USHORT errcode,
const MsgFormat::SafeArg& args)
{
if (checkForShutdown())
{
return;
}
// Append error codes to the status vector
Arg::StatusVector status;
// stuff the error code
status << Arg::Gds(ENCODE_ISC_MSG(errcode, facility));
// stuff params
svc_arg_ptr = svc_arg_conv;
for (unsigned int loop = 0; loop < args.getCount(); ++loop)
{
put_status_arg(status, args.getCell(loop));
}
ERR_post_nothrow(status, &svc_status);
}
void Service::put_status_arg(Arg::StatusVector& status, const MsgFormat::safe_cell& value)
{
using MsgFormat::safe_cell;
switch (value.type)
{
case safe_cell::at_int64:
case safe_cell::at_uint64:
status << Arg::Num(static_cast<SLONG>(value.i_value)); // May truncate number!
break;
case safe_cell::at_str:
status << value.st_value.s_string;
break;
case safe_cell::at_char:
svc_arg_ptr[0] = value.c_value;
svc_arg_ptr[1] = 0;
status << svc_arg_ptr;
svc_arg_ptr += 2;
break;
default:
fb_assert(false);
break;
}
}
void Service::hidePasswd(ArgvType&, int)
{
// no action
}
const FbStatusVector* Service::getStatus()
{
return &svc_status;
}
void Service::initStatus()
{
svc_status->init();
}
void Service::checkService()
{
// no action
}
unsigned int Service::getAuthBlock(const unsigned char** bytes)
{
*bytes = svc_auth_block.hasData() ? svc_auth_block.begin() : NULL;
return svc_auth_block.getCount();
}
void Service::fillDpb(ClumpletWriter& dpb)
{
dpb.insertString(isc_dpb_config, EMBEDDED_PROVIDERS, fb_strlen(EMBEDDED_PROVIDERS));
if (svc_address_path.hasData())
{
dpb.insertData(isc_dpb_address_path, svc_address_path);
}
if (svc_utf8)
{
dpb.insertTag(isc_dpb_utf8_filename);
}
if (svc_crypt_callback)
{
// That's not DPB-related, but anyway should be done before attach/create DB
ISC_STATUS_ARRAY status;
if (fb_database_crypt_callback(status, svc_crypt_callback) != 0)
{
status_exception::raise(status);
}
}
}
bool Service::utf8FileNames()
{
return svc_utf8;
}
Firebird::ICryptKeyCallback* Service::getCryptCallback()
{
return svc_crypt_callback;
}
void Service::need_admin_privs(Arg::StatusVector& status, const char* message)
{
status << Arg::Gds(isc_insufficient_svc_privileges) << Arg::Str(message);
}
bool Service::ck_space_for_numeric(UCHAR*& info, const UCHAR* const end)
{
if ((info + 1 + sizeof(ULONG)) > end)
{
if (info < end)
*info++ = isc_info_truncated;
if (info < end)
*info++ = isc_info_end;
return false;
}
return true;
}
// The SERVER_CAPABILITIES_FLAG is used to mark architectural
// differences across servers. This allows applications like server
// manager to disable features as necessary.
namespace
{
inline ULONG getServerCapabilities()
{
ULONG val = REMOTE_HOP_SUPPORT;
#ifdef WIN_NT
val |= QUOTED_FILENAME_SUPPORT;
#endif // WIN_NT
Firebird::MasterInterfacePtr master;
switch (master->serverMode(-1))
{
case 1: // super
val |= MULTI_CLIENT_SUPPORT;
break;
case 0: // classic
val |= NO_SERVER_SHUTDOWN_SUPPORT;
break;
default: // none-server mode
break;
}
return val;
}
}
Service::Service(const TEXT* service_name, USHORT spb_length, const UCHAR* spb_data,
Firebird::ICryptKeyCallback* crypt_callback)
: svc_status(getPool()), svc_parsed_sw(getPool()),
svc_stdout_head(0), svc_stdout_tail(0), svc_service_run(NULL),
svc_resp_alloc(getPool()), svc_resp_buf(0), svc_resp_ptr(0), svc_resp_buf_len(0),
svc_resp_len(0), svc_flags(SVC_finished), svc_user_flag(0), svc_spb_version(0),
svc_do_shutdown(false), svc_shutdown_in_progress(false), svc_timeout(false),
svc_username(getPool()), svc_sql_role(getPool()), svc_auth_block(getPool()),
svc_expected_db(getPool()), svc_trusted_role(false), svc_utf8(false),
svc_switches(getPool()), svc_perm_sw(getPool()), svc_address_path(getPool()),
svc_command_line(getPool()),
svc_network_protocol(getPool()), svc_remote_address(getPool()), svc_remote_process(getPool()),
svc_remote_pid(0), svc_trace_manager(NULL), svc_crypt_callback(crypt_callback),
svc_existence(FB_NEW_POOL(*getDefaultMemoryPool()) SvcMutex(this)),
svc_stdin_size_requested(0), svc_stdin_buffer(NULL), svc_stdin_size_preload(0),
svc_stdin_preload_requested(0), svc_stdin_user_size(0), svc_thread(0)
#ifdef DEV_BUILD
, svc_debug(false)
#endif
{
initStatus();
{ // scope
// Account service block in global array
MutexLockGuard guard(globalServicesMutex, FB_FUNCTION);
checkForShutdown();
allServices->add(this);
}
// Since this moment we should remove this service from allServices in case of error thrown
try
{
#ifdef DEV_BUILD
// If the service name begins with a slash, ignore it.
if (*service_name == '/' || *service_name == '\\')
service_name++;
string svcname(service_name);
if (svcname == "@@@")
svc_debug = true;
#endif
// Process the service parameter block.
ClumpletReader spb(ClumpletReader::spbList, spb_data, spb_length, spbVersionError);
dumpAuthBlock("Jrd::Service() ctor", &spb, isc_spb_auth_block);
getOptions(spb);
#ifdef DEV_BUILD
if (svc_debug)
{
svc_trace_manager = FB_NEW_POOL(*getDefaultMemoryPool()) TraceManager(this);
svc_user_flag = SVC_user_dba;
return;
}
#endif
// Perhaps checkout the user in the security database.
USHORT user_flag = 0;
if (!svc_username.hasData())
{
if (svc_auth_block.hasData())
{
// remote connection - use svc_auth_block
PathName dummy;
RefPtr<const Config> config;
expandDatabaseName(svc_expected_db, dummy, &config);
Mapping mapping(Mapping::MAP_THROW_NOT_FOUND, svc_crypt_callback);
mapping.needAuthBlock(svc_auth_block);
mapping.setAuthBlock(svc_auth_block);
mapping.setErrorMessagesContextName("services manager");
mapping.setSecurityDbAlias(config->getSecurityDatabase(), nullptr);
string trusted_role;
mapping.mapUser(svc_username, trusted_role);
trusted_role.upper();
svc_trusted_role = trusted_role == ADMIN_ROLE;
}
else
{
// we have embedded service connection, check OS auth
if (ISC_get_user(&svc_username, NULL, NULL))
svc_username = DBA_USER_NAME;
}
}
if (!svc_username.hasData())
{
// user name and password are required while
// attaching to the services manager
status_exception::raise(Arg::Gds(isc_service_att_err) << Arg::Gds(isc_svcnouser));
}
if (svc_username.length() > USERNAME_LENGTH)
{
status_exception::raise(Arg::Gds(isc_long_login) <<
Arg::Num(svc_username.length()) << Arg::Num(USERNAME_LENGTH));
}
// Check that the validated user has the authority to access this service
if (svc_username != DBA_USER_NAME && !svc_trusted_role)
user_flag = SVC_user_any;
else
user_flag = SVC_user_dba | SVC_user_any;
// move service switches in
string switches = svc_command_line;
svc_flags |= switches.hasData() ? SVC_cmd_line : 0;
svc_perm_sw = switches;
svc_user_flag = user_flag;
svc_trace_manager = FB_NEW_POOL(*getDefaultMemoryPool()) TraceManager(this);
} // try
catch (const Firebird::Exception& ex)
{
TraceManager* trace_manager = NULL;
FbLocalStatus status_vector;
try
{
// Use created trace manager if it's possible
const bool hasTrace = svc_trace_manager != NULL;
if (hasTrace)
trace_manager = svc_trace_manager;
else
trace_manager = FB_NEW_POOL(*getDefaultMemoryPool()) TraceManager(this);
if (trace_manager->needs(ITraceFactory::TRACE_EVENT_SERVICE_ATTACH))
{
ex.stuffException(&status_vector);
const ISC_STATUS exc = status_vector[1];
const bool no_priv = (exc == isc_login || exc == isc_no_priv);
TraceServiceImpl service(this);
trace_manager->event_service_attach(&service,
no_priv ? ITracePlugin::RESULT_UNAUTHORIZED : ITracePlugin::RESULT_FAILED);
}
if (!hasTrace)
delete trace_manager;
}
catch (const Firebird::Exception&)
{
}
removeFromAllServices();
throw;
}
if (svc_trace_manager->needs(ITraceFactory::TRACE_EVENT_SERVICE_ATTACH))
{
TraceServiceImpl service(this);
svc_trace_manager->event_service_attach(&service, ITracePlugin::RESULT_SUCCESS);
}
}
static THREAD_ENTRY_DECLARE svcShutdownThread(THREAD_ENTRY_PARAM)
{
if (fb_shutdown(10 * 1000 /* 10 seconds */, fb_shutrsn_services) == FB_SUCCESS)
{
InstanceControl::registerShutdown(0);
exit(0);
}
return 0;
}
void Service::detach()
{
ExistenceGuard guard(this, FB_FUNCTION);
if (svc_flags & SVC_detached)
{
// Service was already detached
Arg::Gds(isc_bad_svc_handle).raise();
}
// save it cause after call to finish() we can't access class members any more
const bool localDoShutdown = svc_do_shutdown;
TraceServiceImpl service(this);
svc_trace_manager->event_service_detach(&service, ITracePlugin::RESULT_SUCCESS);
// Mark service as detached.
finish(SVC_detached);
if (localDoShutdown)
{
// run in separate thread to avoid blocking in remote
Thread::start(svcShutdownThread, 0, THREAD_medium);
}
}
Service::~Service()
{
removeFromAllServices();
delete svc_trace_manager;
svc_trace_manager = NULL;
fb_assert(svc_existence->locked());
svc_existence->link = NULL;
}
void Service::removeFromAllServices()
{
MutexLockGuard guard(globalServicesMutex, FB_FUNCTION);
FB_SIZE_T pos;
if (locateInAllServices(&pos))
{
allServices->remove(pos);
return;
}
fb_assert(false);
}
bool Service::locateInAllServices(FB_SIZE_T* posPtr)
{
MutexLockGuard guard(globalServicesMutex, FB_FUNCTION);
AllServices& all(allServices);
for (FB_SIZE_T pos = 0; pos < all.getCount(); ++pos)
{
if (all[pos] == this)
{
if (posPtr)
{
*posPtr = pos;
}
return true;
}
}
return false;
}
ULONG Service::totalCount()
{
MutexLockGuard guard(globalServicesMutex, FB_FUNCTION);
AllServices& all(allServices);
ULONG cnt = 0;
// don't count already detached services
for (FB_SIZE_T i = 0; i < all.getCount(); i++)
{
if (!(all[i]->svc_flags & SVC_detached))
cnt++;
}
return cnt;
}
bool Service::checkForShutdown()