FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
rstudio/src/cpp/core/system/PosixSystem.cpp at main · ssh352/rstudio · GitHub
ssh352
/
rstudio
Public
forked from
rstudio/rstudio
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
rstudio
/
src
/
cpp
/
core
/
system
/
PosixSystem.cpp
Copy path
More file actions
More file actions
Latest commit
History
History
History
2846 lines (2384 loc) · 74.6 KB
Breadcrumbs
rstudio
/
src
/
cpp
/
core
/
system
/
PosixSystem.cpp
Copy path
File metadata and controls
2846 lines (2384 loc) · 74.6 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
/*
* PosixSystem.cpp
*
* Copyright (C) 2022 by Posit Software, PBC
*
* Unless you have received this program directly from Posit Software pursuant
* to the terms of a commercial license agreement with Posit Software, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#
include
<
core/system/PosixSystem.hpp
>
#
include
<
stdio.h
>
#
include
<
iostream
>
#
include
<
string
>
#
include
<
vector
>
#
include
<
boost/algorithm/string.hpp
>
#
include
<
boost/range/as_array.hpp
>
#
include
<
boost/bind/bind.hpp
>
#
include
<
boost/scope_exit.hpp
>
#
include
<
signal.h
>
#
include
<
fcntl.h
>
#
include
<
syslog.h
>
#
include
<
sys/resource.h
>
#
include
<
sys/wait.h
>
#
include
<
sys/stat.h
>
#
include
<
unistd.h
>
#
include
<
pwd.h
>
#
include
<
grp.h
>
#
include
<
sys/types.h
>
#
include
<
sys/socket.h
>
#
include
<
uuid/uuid.h
>
#
include
<
shared_core/system/PosixSystem.hpp
>
#
ifdef
__APPLE__
#
include
<
mach-o/dyld.h
>
#
include
<
sys/proc_info.h
>
#
include
<
libproc.h
>
#
include
<
gsl/gsl
>
#
endif
#
ifdef
__linux__
#
include
<
sys/prctl.h
>
#
include
<
sys/sysinfo.h
>
#
include
<
linux/kernel.h
>
//
Some data structures here don't compile on rhel8 due to 'private' being used as a symbol???
//
so defining them again here
//
#include <linux/keyctl.h>
#
define
KEYCTL_JOIN_SESSION_KEYRING
1
/*
join or start named session keyring
*/
#
define
KEYCTL_LINK
8
/*
link a key into a keyring
*/
#
define
KEY_SPEC_SESSION_KEYRING
-
3
/*
- key ID for session-specific keyring
*/
#
define
KEY_SPEC_USER_KEYRING
-
4
/*
- key ID for UID-specific keyring
*/
#
include
<
dirent.h
>
#
include
<
stdarg.h
>
#
include
<
sys/syscall.h
>
#
endif
#
include
<
boost/thread.hpp
>
#
include
<
boost/format.hpp
>
#
include
<
boost/lexical_cast.hpp
>
#
include
<
boost/range.hpp
>
#
include
<
boost/algorithm/string/replace.hpp
>
#
include
<
boost/algorithm/string/split.hpp
>
#
include
<
core/RegexUtils.hpp
>
#
include
<
core/Algorithm.hpp
>
#
include
<
core/DateTime.hpp
>
#
include
<
core/FileInfo.hpp
>
#
include
<
core/FileSerializer.hpp
>
#
include
<
core/Exec.hpp
>
#
include
<
core/LogOptions.hpp
>
#
include
<
core/StringUtils.hpp
>
#
include
<
shared_core/SafeConvert.hpp
>
#
include
<
core/FileSerializer.hpp
>
#
include
<
core/Thread.hpp
>
#
include
<
core/system/ProcessArgs.hpp
>
#
include
<
core/system/Environment.hpp
>
#
include
<
core/system/FileScanner.hpp
>
#
include
<
core/system/PosixUser.hpp
>
#
include
<
core/system/PosixGroup.hpp
>
#
include
<
core/system/Process.hpp
>
#
include
<
core/system/ShellUtils.hpp
>
#
include
<
core/system/User.hpp
>
#
include
<
shared_core/Error.hpp
>
#
include
<
shared_core/FilePath.hpp
>
#
include
<
shared_core/system/User.hpp
>
#
include
"
config.h
"
using
namespace
boost
::placeholders
;
namespace
rstudio
{
namespace
core
{
namespace
system
{
namespace
{
int
signalForType
(SignalType type)
{
switch
(type)
{
case
SigInt:
return
SIGINT
;
case
SigHup:
return
SIGHUP
;
case
SigAbrt:
return
SIGABRT
;
case
SigSegv:
return
SIGSEGV
;
case
SigIll:
return
SIGILL
;
case
SigUsr1:
return
SIGUSR1
;
case
SigUsr2:
return
SIGUSR2
;
case
SigPipe:
return
SIGPIPE
;
case
SigChld:
return
SIGCHLD
;
case
SigTerm:
return
SIGTERM
;
default
:
return
-
1
;
}
}
}
//
anonymous namespace
Error
realPath
(
const
FilePath& filePath, FilePath* pRealPath)
{
std::string path =
string_utils::utf8ToSystem
(filePath.
getAbsolutePath
());
char
buffer[
PATH_MAX
*
2
];
char
* realPath = ::
realpath
(path.
c_str
(), buffer);
if
(realPath ==
nullptr
)
{
Error error =
systemError
(errno,
ERROR_LOCATION
);
error.
addProperty
(
"
path
"
, filePath);
return
error;
}
*pRealPath =
FilePath
(
string_utils::systemToUtf8
(realPath));
return
Success
();
}
Error
realPath
(
const
std::string& path, FilePath* pRealPath)
{
char
buffer[
PATH_MAX
*
2
];
char
* realPath = ::
realpath
(path.
c_str
(), buffer);
if
(realPath ==
nullptr
)
{
Error error =
systemError
(errno,
ERROR_LOCATION
);
error.
addProperty
(
"
path
"
, path);
return
error;
}
*pRealPath =
FilePath
(realPath);
return
Success
();
}
void
initHook
()
{
}
Error
findProgramOnPath
(
const
std::string& program,
core::FilePath* pProgramPath)
{
std::string path =
core::system::getenv
(
"
PATH
"
);
auto
paths =
core::algorithm::split
(path,
"
:
"
);
for
(
auto
&& path : paths)
{
//
get file descriptor for path entry
int
fd = ::
open
(path.
c_str
(),
0
);
if
(fd == -
1
)
continue
;
//
clean up when we're done
BOOST_SCOPE_EXIT
( (&fd) )
{
::close
(fd);
}
BOOST_SCOPE_EXIT_END
;
//
confirm that it's a regular file
struct
stat
sb;
int
status = ::
fstatat
(fd, program.
c_str
(), &sb,
0
);
if
(status == -
1
)
continue
;
bool
isRegularFile =
S_ISREG
(sb.
st_mode
);
if
(!isRegularFile)
continue
;
//
confirm that it's executable
//
note that we use AT_EACCESS to ensure checks are done using
//
the effective user id
status = ::
faccessat
(fd, program.
c_str
(),
X_OK
,
AT_EACCESS
);
if
(status == -
1
)
continue
;
//
all checks passed; return full path
*pProgramPath =
FilePath
(path).
completeChildPath
(program);
return
Success
();
}
return
fileNotFoundError
(program,
ERROR_LOCATION
);
}
//
statics defined in System.cpp
extern
boost::shared_ptr<log::LogOptions> s_logOptions;
extern
boost::recursive_mutex s_loggingMutex;
extern
std::string s_programIdentity;
Error
initializeSystemLog
(
const
std::string& programIdentity,
log::LogLevel logLevel,
bool
enableConfigReload)
{
RECURSIVE_LOCK_MUTEX
(s_loggingMutex)
{
//
create default syslog logger options
log::SysLogOptions options;
s_logOptions.
reset
(
new
log::LogOptions
(programIdentity, logLevel, log::LoggerType::
kSysLog
, log::LogMessageFormatType::
PRETTY
, options));
s_programIdentity = programIdentity;
Error error =
initLog
();
if
(error)
return
error;
}
END_LOCK_MUTEX
if
(enableConfigReload)
initializeLogConfigReload
();
return
Success
();
}
boost::function<
void
()> s_sighupHandler;
namespace
{
void
logConfigReloadThreadFunc
(
sigset_t
waitMask)
{
for
(;;)
{
//
wait for SIGHUP
int
sig =
0
;
int
result = ::
sigwait
(&waitMask, &sig);
if
(result !=
0
)
return
;
if
(sig ==
SIGHUP
)
{
LOG_INFO_MESSAGE
(
"
Reloading logging configuration...
"
);
Error error =
reinitLog
();
if
(error)
{
LOG_ERROR
(error);
LOG_ERROR_MESSAGE
(
"
Failed to reload logging configuration
"
);
}
else
{
LOG_INFO_MESSAGE
(
"
Successfully reloaded logging configuration
"
);
}
//
call previously registered SIGHUP handlder
if
(s_sighupHandler)
s_sighupHandler
();
}
}
}
}
//
anonymous namespace
void
initializeLogConfigReload
()
{
//
block the SIGHUP signal
sigset_t
waitMask;
sigemptyset
(&waitMask);
sigaddset
(&waitMask,
SIGHUP
);
int
result = ::
pthread_sigmask
(
SIG_BLOCK
, &waitMask,
nullptr
);
if
(result !=
0
)
return
;
//
start a thread to handle the SIGHUP signal
boost::thread
thread
(
boost::bind
(logConfigReloadThreadFunc, waitMask));
}
void
registerSighupHandler
(
const
boost::function<
void
()>& sighupHandler)
{
s_sighupHandler = sighupHandler;
}
Error
ignoreTerminalSignals
()
{
ExecBlock ignoreBlock;
ignoreBlock.
addFunctions
()
(
boost::bind
(posix::ignoreSignal,
SIGHUP
))
(
boost::bind
(posix::ignoreSignal,
SIGTSTP
))
(
boost::bind
(posix::ignoreSignal,
SIGTTOU
))
(
boost::bind
(posix::ignoreSignal,
SIGTTIN
));
return
ignoreBlock.
execute
();
}
Error
ignoreChildExits
()
{
#
if
defined(HAVE_SA_NOCLDWAIT)
//
POSIX compliant
struct
sigaction
reapchildren;
::memset
( &reapchildren,
0
,
sizeof
reapchildren );
reapchildren.
sa_flags
=
SA_NOCLDWAIT
;
int
result = ::
sigaction
(
SIGCHLD
, &reapchildren,
0
);
if
(result !=
0
)
return
systemError
(result,
ERROR_LOCATION
);
#
else
//
other systems
if
(::
signal
(
SIGCHLD
,
SIG_IGN
) ==
SIG_ERR
)
return
systemError
(errno,
ERROR_LOCATION
);
#
endif
//
NO_CLDWAIT
return
Success
();
}
namespace
{
void
handleSIGCHLD
(
int
sig)
{
int
stat;
while
(::
waitpid
(-
1
, &stat,
WNOHANG
) >
0
)
{
}
}
}
Error
reapChildren
()
{
//
setup signal handler
struct
sigaction
sa;
::memset
(&sa,
0
,
sizeof
sa);
sa.
sa_handler
= handleSIGCHLD;
sigemptyset
(&sa.
sa_mask
);
sa.
sa_flags
=
SA_RESTART
;
//
install it
int
result = ::
sigaction
(
SIGCHLD
, &sa,
nullptr
);
if
(result !=
0
)
return
systemError
(errno,
ERROR_LOCATION
);
else
return
Success
();
}
//
SignalBlocker -- block signals in a scope
//
//
NOTE: boost has a portable signal_blocker class however we don't use it b/c:
//
1) it is in the detail namespace (which isn't a public api)
//
2) it doesn't check or fail on errors
//
//
NOTE: blocking signals in threads and then handling them on either the
//
main thread or a dedicated thread will only work properly on Linux kernel
//
v2.6 or higher (because it supports the Native POSIX Thread Library and
//
thus delivers signals to multi-threaded programs in a POSIX compliant way)
struct
SignalBlocker
::Impl
{
Impl
() : blocked(
false
) {}
bool
blocked;
sigset_t
oldMask;
Error
block
(
sigset_t
* pBlockMask)
{
//
install mask
int
result = ::
pthread_sigmask
(
SIG_BLOCK
, pBlockMask, &oldMask);
if
(result !=
0
)
return
systemError
(result,
ERROR_LOCATION
);
//
set restore bit and return success
blocked =
true
;
return
Success
();
}
};
SignalBlocker::SignalBlocker
()
: pImpl_(
new
Impl())
{
}
Error
SignalBlocker::block
(SignalType signal)
{
//
get signal
int
sig =
signalForType
(signal);
if
(sig <
0
)
return
systemError
(
EINVAL
,
ERROR_LOCATION
);
//
create a mask for blocking the signal
sigset_t
blockMask;
sigemptyset
(&blockMask);
sigaddset
(&blockMask, sig);
//
block
return
pImpl_->
block
(&blockMask);
}
Error
SignalBlocker::blockAll
()
{
//
create mask to block all signals
sigset_t
blockMask;
sigfillset
(&blockMask);
//
block
return
pImpl_->
block
(&blockMask);
}
SignalBlocker::~SignalBlocker
()
{
try
{
if
(pImpl_->
blocked
)
{
//
restore old mask
int
result = ::
pthread_sigmask
(
SIG_SETMASK
, &(pImpl_->
oldMask
),
nullptr
);
if
(result !=
0
)
LOG_ERROR
(
systemError
(result,
ERROR_LOCATION
));
}
}
catch
(...)
{
}
}
Error
clearSignalMask
()
{
int
result =
signal_safe::clearSignalMask
();
if
(result !=
0
)
return
systemError
(result,
ERROR_LOCATION
);
else
return
Success
();
}
Error
handleSignal
(SignalType signal,
void
(*handler)(
int
))
{
int
sig =
signalForType
(signal);
if
(sig <
0
)
return
systemError
(
EINVAL
,
ERROR_LOCATION
);
::signal
(sig, handler);
return
Success
();
}
core::Error
ignoreSignal
(SignalType signal)
{
int
sig =
signalForType
(signal);
if
(sig <
0
)
return
systemError
(
EINVAL
,
ERROR_LOCATION
);
return
posix::ignoreSignal
(sig);
}
Error
useDefaultSignalHandler
(SignalType signal)
{
int
sig =
signalForType
(signal);
if
(sig <
0
)
return
systemError
(
EINVAL
,
ERROR_LOCATION
);
struct
sigaction
sa;
::memset
(&sa,
0
,
sizeof
sa);
sa.
sa_handler
=
SIG_DFL
;
int
result = ::
sigaction
(sig, &sa,
nullptr
);
if
(result !=
0
)
{
Error error =
systemError
(result,
ERROR_LOCATION
);
return
error;
}
else
{
return
Success
();
}
}
void
sendSignalToSelf
(SignalType signal)
{
::kill
(::getpid(), signalForType(signal));
}
std::string
username
()
{
return
system::getenv
(
"
USER
"
);
}
unsigned
int
effectiveUserId
()
{
return
::
geteuid
();
}
FilePath
userHomePath
(std::string envOverride)
{
return
User::getUserHomePath
(envOverride);
}
FilePath
userSettingsPath
(
const
FilePath& userHomeDirectory,
const
std::string& appName,
bool
ensureDirectory)
{
std::string lower = appName;
boost::to_lower
(lower);
FilePath path = userHomeDirectory.
completeChildPath
(
"
.
"
+ lower);
if
(ensureDirectory)
{
Error error = path.
ensureDirectory
();
if
(error)
{
LOG_ERROR
(error);
}
}
return
path;
}
bool
currentUserIsPrivilleged
(
unsigned
int
minimumUserId)
{
return
::
geteuid
() < minimumUserId;
}
namespace
{
//
NOTE: this function is duplicated between here and core::system
//
Did this to prevent the "system" interface from allowing Posix
//
constructs with Win32 no-ops to creep in (since this is used on
//
Posix for forking and has no purpose on Win32)
//
There is no fully reliable and cross-platform way to do this, see:
//
//
Various potential mechanisms include:
//
//
- closefrom
//
- fcntl(0, F_MAXFD)
//
- sysconf(_SC_OPEN_MAX)
//
- getrlimit(RLIMIT_NOFILE, &rl)
//
- gettdtablesize
//
- read from /proc/self/fd, /proc/<pid>/fd, or /dev/fd
//
//
Note that the above functions may return either -1 or MAX_INT, in
//
which case substituting/truncating to an appropriate number (1024?)
//
is still required
#
if
!defined(__APPLE__) && !defined(HAVE_PROCSELF)
//
worst case scenario - close all file descriptors possible
//
this can be EXTREMELY slow when max fd is set to a high value
//
note: this conditional should actually never be true
//
as all linux systems have /proc/self - this is preserved in the codebase
//
as a remainder of what was being done in the recent past
Error
closeFileDescriptorsFrom
(
int
fdStart)
{
//
get limit
struct
rlimit
rl;
if
(::
getrlimit
(
RLIMIT_NOFILE
, &rl) <
0
)
return
systemError
(errno,
ERROR_LOCATION
);
if
(rl.
rlim_max
==
RLIM_INFINITY
)
rl.
rlim_max
=
1024
;
//
default on linux
//
close file descriptors
for
(
int
i=fdStart; i< (
int
)rl.
rlim_max
; i++)
{
if
(::
close
(i) <
0
&& errno !=
EBADF
)
return
systemError
(errno,
ERROR_LOCATION
);
}
return
Success
();
}
#
else
//
read the file descriptors from a virtual directory listing,
//
iterate over them and close - much faster than the above method
Error
closeFileDescriptorsFrom
(
int
fdStart)
{
std::vector<
unsigned
int
> fds;
Error error =
getOpenFds
(&fds);
if
(error)
return
error;
for
(
int
fd : fds)
{
if
(fd >= fdStart)
{
if
(::
close
(fd) <
0
&& errno !=
EBADF
)
return
systemError
(errno,
ERROR_LOCATION
);
}
}
return
Success
();
}
#
endif
}
//
anonymous namespace
Error
getOpenFds
(std::vector<
uint32_t
>* pFds)
{
return
getOpenFds
(
getpid
(), pFds);
}
#
ifndef
__APPLE__
Error
getOpenFds
(
pid_t
pid, std::vector<
uint32_t
>* pFds)
{
std::string pidStr =
safe_convert::numberToString
(pid);
boost::format
fmt
(
"
/proc/%1%/fd
"
);
FilePath
filePath
(
boost::str
(fmt % pidStr));
//
note: we use a FileScanner to list the pids instead of using boost
//
(FilePath class), because there is a bug in boost filesystem where
//
directory iterators can segfault under heavy load while reading the /proc filesystem
//
there aren't many details on this, but see https://svn.boost.org/trac10/ticket/10450
core::system::FileScannerOptions options;
options.
recursive
=
false
;
tree<FileInfo> subDirs;
Error error =
core::system::scanFiles
(
core::toFileInfo
(filePath), options, &subDirs);
if
(error)
return
error;
for
(
const
FileInfo& info : subDirs)
{
FilePath
path
(info.
absolutePath
());
boost::optional<
uint32_t
> fd = safe_convert::stringTo<
uint32_t
>(path.
getFilename
());
if
(fd)
{
pFds->
push_back
(fd.
get
());
}
}
return
Success
();
}
#
else
Error
getOpenFds
(
pid_t
pid, std::vector<
uint32_t
> *pFds)
{
//
get size of the buffer needed to hold the list of fds
int
bufferSize =
proc_pidinfo
(pid,
PROC_PIDLISTFDS
,
0
,
0
,
0
);
if
(bufferSize == -
1
)
return
systemError
(errno,
ERROR_LOCATION
);
//
get the list of open fds
struct
proc_fdinfo
* procFdInfo =
static_cast
<
struct
proc_fdinfo
*>(
malloc
(bufferSize));
if
(!procFdInfo)
return
systemError
(boost::system::errc::not_enough_memory,
ERROR_LOCATION
);
int
filledSize =
proc_pidinfo
(pid,
PROC_PIDLISTFDS
,
0
, procFdInfo, bufferSize);
int
numFds = filledSize /
PROC_PIDLISTFD_SIZE
;
for
(
int
i =
0
; i < numFds; ++i)
{
pFds->
push_back
(procFdInfo[i].
proc_fd
);
}
free
(procFdInfo);
return
Success
();
}
#
endif
Error
closeAllFileDescriptors
()
{
return
closeFileDescriptorsFrom
(
0
);
}
Error
closeNonStdFileDescriptors
()
{
return
closeFileDescriptorsFrom
(
STDERR_FILENO
+
1
);
}
Error
closeChildFileDescriptorsFrom
(
pid_t
childPid,
int
pipeFd,
uint32_t
fdStart)
{
std::
size_t
written;
std::vector<
uint32_t
> fds;
Error error =
getOpenFds
(childPid, &fds);
if
(!error)
{
for
(
uint32_t
fd : fds)
{
error = posix::posixCall<std::
size_t
>(
boost::bind
(
::write,
pipeFd,
&fd,
4
),
ERROR_LOCATION
,
&written);
if
(error)
{
return
error;
}
}
}
else
{
//
we simply log the error instead of returning it because this is generally benign and can
//
happen in certain normal scenarios, such as if /proc/x/fd is only readable by root
//
(if core dumps are turned off)
core::log::logErrorAsDebug
(error);
}
//
write message close (-1) even if we failed to retrieve pids above
//
this prevents the child from being stuck in limbo or interpreting its
//
actual stdin as fds
int
close = -
1
;
Error closeError = posix::posixCall<std::
size_t
>(
boost::bind
(
::write,
pipeFd,
&close,
4
),
ERROR_LOCATION
,
&written);
if
(closeError)
{
return
error;
}
return
closeError;
}
namespace
signal_safe
{
namespace
{
void
safeClose
(
uint32_t
fd)
{
while
(::
close
(fd) == -
1
)
{
//
keep trying the close operation if it was interrupted
//
otherwise, the file descriptor is not open, so return
if
(errno !=
EINTR
)
break
;
}
}
//
worst case scenario - close all file descriptors possible
//
this can be EXTREMELY slow when max fd is set to a high value
void
closeFileDescriptorsFromSafe
(
uint32_t
fdStart,
rlim_t
fdLimit)
{
//
safe function is best effort - swallow all errors
//
this is necessary when invoked in a signal handler or
//
during a fork in multithreaded processes to prevent hangs
if
(fdLimit ==
RLIM_INFINITY
)
fdLimit =
1024
;
//
default on linux
//
close file descriptors
for
(
uint32_t
i = fdStart; i < fdLimit; ++i)
{
safeClose
(i);
}
}
}
//
anonymous namespace
void
closeNonStdFileDescriptors
(
rlim_t
fdLimit)
{
closeFileDescriptorsFromSafe
(
STDERR_FILENO
+
1
, fdLimit);
}
void
closeFileDescriptorsFromParent
(
int
pipeFd,
uint32_t
fdStart,
rlim_t
fdLimit)
{
//
read fds that we own from parent process pipe until we've read them all
//
the parent must give us this list because we cannot fetch it ourselves
//
in a signal-safe way, but we can read from the pipe safely
bool
error =
false
;
bool
fdsRead =
false
;
int32_t
buff;
while
(
true
)
{
ssize_t
bytesRead = ::
read
(pipeFd, &buff,
4
);
//
check for error
if
(bytesRead == -
1
|| bytesRead ==
0
)
{
if
(errno !=
EINTR
&&
errno !=
EAGAIN
)
{
error =
true
;
break
;
}
continue
;
}
//
determine which fd was just read from the parent
if
(buff == -
1
)
{
break
;
//
indicates no more fds are open by the process
}
fdsRead =
true
;
uint32_t
fd =
static_cast
<
uint32_t
>(buff);
//
close the reported fd if it is in range
if
(fd >= fdStart && fd < fdLimit && buff != pipeFd)
safeClose
(fd);
}
//
if no descriptors could be read from the parent for whatever reason,
//
or there was an error reading from the pipe,
//
fall back to the slow close method detailed above
if
(error || !fdsRead)
{
closeFileDescriptorsFromSafe
(fdStart, pipeFd);
closeFileDescriptorsFromSafe
(pipeFd +
1
, fdLimit);
}
}
int
permanentlyDropPriv
(UidType newUid)
{
return
::
setuid
(newUid);
}
int
restoreRoot
()
{
return
::
setuid
(
0
);
}
int
clearSignalMask
()
{
sigset_t
blockNoneMask;
sigemptyset
(&blockNoneMask);
return
::
pthread_sigmask
(
SIG_SETMASK
, &blockNoneMask,
nullptr
);
}
}
//
namespace signal_safe
void
closeStdFileDescriptors
()
{
::close
(
STDIN_FILENO
);
::close
(
STDOUT_FILENO
);
::close
(
STDERR_FILENO
);
}
void
attachStdFileDescriptorsToDevNull
()
{
int
fd0 = ::
open
(
"
/dev/null
"
,
O_RDWR
);
if
(fd0 == -
1
)
LOG_ERROR
(
systemError
(errno,
ERROR_LOCATION
));
int
fd1 = ::
dup
(fd0);
if
(fd1 == -
1
)
LOG_ERROR
(
systemError
(errno,
ERROR_LOCATION
));
int
fd2 = ::
dup
(fd0);
if
(fd2 == -
1
)
LOG_ERROR
(
systemError
(errno,
ERROR_LOCATION
));
}
void
setStandardStreamsToDevNull
()
{
core::system::closeStdFileDescriptors
();
core::system::attachStdFileDescriptorsToDevNull
();
std::ios::sync_with_stdio
();
}
bool
isHiddenFile
(
const
FilePath& filePath)
{
std::string filename = filePath.
getFilename
();
return
(!filename.
empty
() && (filename[
0
] ==
'
.
'
));
}
bool
isHiddenFile
(
const
FileInfo& fileInfo)
{
return
isHiddenFile
(
FilePath
(fileInfo.
absolutePath
()));
}
bool
isReadOnly
(
const
FilePath& filePath)
{
if
(::
access
(filePath.
getAbsolutePath
().
c_str
(),
W_OK
) == -
1
)
{
if
(errno ==
EACCES
)
{
return
true
;
}
else
{
Error error =
systemError
(errno,
ERROR_LOCATION
);
error.
addProperty
(
"
path
"
, filePath);
LOG_ERROR
(error);
return
false
;
}
}
else
{
return
false
;
}
}
bool
stderrIsTerminal
()
{
return
::
isatty
(
STDERR_FILENO
) ==
1
;
}
bool
stdoutIsTerminal
()
{
return
::
isatty
(
STDOUT_FILENO
) ==
1
;
}
std::string
generateUuid
(
bool
includeDashes)
{
//
generaate the uuid and convert it to a strting
uuid_t
uuid;
::uuid_generate_random
(uuid);
char
uuidBuffer[
40
];
::uuid_unparse_lower
(uuid, uuidBuffer);
std::string
uuidStr
(uuidBuffer);
//
remove dashes if requested
if
(!includeDashes)
boost::algorithm::replace_all
(uuidStr,
"
-
"
,
"
"
);
return
uuidStr;
}
PidType
currentProcessId
()
{
return
::
getpid
();
}
Error
executablePath
(
int
argc,
char
*
const
argv[],
FilePath* pExecutablePath)
{
return
executablePath
(argv[
0
], pExecutablePath);
}
Error
executablePath
(
const
char
* argv0,
FilePath* pExecutablePath)
{
std::string executablePath;
#
if
defined(__APPLE__)
//
get path to current executable
uint32_t
buffSize =
2048
;
std::vector<
char
>
buffer
(buffSize);
if
(
_NSGetExecutablePath
(&(buffer[
0
]), &buffSize) == -
1
)
{
buffer.
resize
(buffSize);
_NSGetExecutablePath
(&(buffer[
0
]), &buffSize);
}
//
set it
executablePath =
std::string
(&(buffer[
0
]));
#
elif
defined(HAVE_PROCSELF)
executablePath =
std::string
(
"
/proc/self/exe
"
);
#
else
//
Note that this technique will NOT work if the executable was located
//
via a search of the PATH. To make this fallback fully robust we would
//
need to also search the PATH for the exe name in argv[0]
//
//
use argv[0] and initial path
FilePath initialPath =
FilePath::initialPath
();
executablePath = initialPath.
completePath
(argv0).
getAbsolutePath
();
#
endif
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL