-
Notifications
You must be signed in to change notification settings - Fork 0
/
Posix.Daemon.pas
303 lines (251 loc) · 7.55 KB
/
Posix.Daemon.pas
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
{******************************************************************************}
{ }
{ WiRL: RESTful Library for Delphi }
{ }
{ Copyright (c) 2015-2017 WiRL Team }
{ }
{ https://github.com/delphi-blocks/WiRL }
{ }
{******************************************************************************}
unit Posix.Daemon;
interface
{$SCOPEDENUMS ON}
uses
System.SysUtils,
Posix.Stdlib,
Posix.SysStat,
Posix.SysTypes,
Posix.Unistd,
Posix.Signal,
Posix.Fcntl,
System.IOUtils,
Posix.Syslog;
/// <summary>
/// global procedure (cdecl) to handle signals
/// </summary>
procedure HandleSignals(ASigNum: Integer); cdecl;
type
{ TODO -opaolo -c : supports more signals 12/06/2017 11:43:40 }
TPosixSignal = (Termination, Reload);
/// <summary>
/// Anonymous method signature
/// </summary>
TSignalProc = reference to procedure (ASignal: TPosixSignal);
/// <summary>
/// Class to define and run a Posix daemon. For more information please
/// read the Linux manpages: man 7 daemon
/// </summary>
TPosixDaemon = class
private class var
FRunning: Boolean;
FProcessID: pid_t;
FSignalProc: TSignalProc;
public const
/// <summary>
/// Missing from linux/StdlibTypes.inc !!! <stdlib.h>
/// </summary>
EXIT_SUCCESS = 0;
EXIT_FAILURE = 1;
private
/// <summary>
/// Fork a Posix process
/// </summary>
/// <remarks>
/// Do not create (and run) any thread before forking a process
/// </remarks>
class function ForkProcess: pid_t; static;
/// <summary>
/// Close all opened file descriptors
/// </summary>
class procedure CloseDescriptors; static;
/// <summary>
/// Redirect stdin, stdout, stderr to /dev/null
/// </summary>
class procedure RouteDescriptors; static;
/// <summary>
/// Catch, ignore and handle signals
/// </summary>
class procedure CatchHandleSignals; static;
/// <summary>
/// Kill the first process and leave only the daemon
/// </summary>
class procedure KillParent(APID: pid_t); static;
/// <summary>
/// Detach from any terminal and create an independent session.
/// </summary>
class procedure DetachTerminal; static;
/// <summary>
/// Set new file permissions: Restrict file creation mode to 750
/// </summary>
class procedure SetRootDirectory(const ADirectory: string); static;
/// <summary>
/// Change the current directory to the root directory (/), in order to
/// avoid that the daemon involuntarily blocks mount points from being unmounted
/// </summary>
class procedure UserFileMask(AMask: Cardinal); static;
public
/// <summary>
/// Console setup method, to be called before Run and before starting
/// any thread in the application
/// </summary>
class procedure Setup(ASignalProc: TSignalProc);
/// <summary>
/// Infinte console loop
/// </summary>
class procedure Run(AInterval: Integer); static;
/// <summary>
/// Stop the daemon
/// </summary>
class procedure Stop; static;
/// <summary>
/// Open the log connection
/// </summary>
class procedure LogOpen; static;
/// <summary>
/// Log Info message
/// </summary>
class procedure LogInfo(const AMessage: string); static;
/// <summary>
/// Log Warning message
/// </summary>
class procedure LogWarning(const AMessage: string); static;
/// <summary>
/// Log Error message
/// </summary>
class procedure LogError(const AMessage: string); static;
/// <summary>
/// Log Info Raw message
/// </summary>
class procedure LogRaw(const AMessage: string); static;
/// <summary>
/// Close the log connection
/// </summary>
class procedure LogClose; static;
/// <summary>
/// Posix Process ID (pid)
/// </summary>
class property ProcessID: pid_t read FProcessID write FProcessID;
end;
implementation
procedure HandleSignals(ASigNum: Integer);
begin
case ASigNum of
SIGTERM:
begin
TPosixDaemon.LogInfo('Signal SIGTERM received');
TPosixDaemon.FSignalProc(TPosixSignal.Termination);
TPosixDaemon.FRunning := False;
end;
SIGHUP:
begin
TPosixDaemon.LogInfo('Signal SIGHUP received');
TPosixDaemon.FSignalProc(TPosixSignal.Reload);
end;
end;
end;
{ TPosixDaemon }
class procedure TPosixDaemon.CloseDescriptors;
var
LIndex: Integer;
begin
for LIndex := sysconf(_SC_OPEN_MAX) downto 0 do
__close(LIndex);
end;
class procedure TPosixDaemon.DetachTerminal;
begin
if setsid() < 0 then
raise Exception.Create('Impossible to create an independent session');
end;
class function TPosixDaemon.ForkProcess: pid_t;
begin
Result := fork();
if Result < 0 then
raise Exception.Create('Cannot create the fork');
end;
class procedure TPosixDaemon.CatchHandleSignals;
begin
signal(SIGCHLD, TSignalHandler(SIG_IGN));
signal(SIGHUP, HandleSignals);
signal(SIGTERM, HandleSignals);
end;
class procedure TPosixDaemon.KillParent(APID: pid_t);
begin
// If the PID returned from fork() is valid, the parent process
// must terminate gracefully
if APID > 0 then
Halt(TPosixDaemon.EXIT_SUCCESS);
end;
class procedure TPosixDaemon.LogClose;
begin
closelog;
end;
class procedure TPosixDaemon.LogError(const AMessage: string);
begin
syslog(LOG_ERR, AMessage);
end;
class procedure TPosixDaemon.LogInfo(const AMessage: string);
begin
syslog(LOG_INFO, AMessage);
end;
class procedure TPosixDaemon.LogWarning(const AMessage: string);
begin
syslog(LOG_WARNING, AMessage);
end;
class procedure TPosixDaemon.LogOpen;
begin
// syslog() will call LogOpen() with no arguments if the log is not currently open.
openlog(nil, LOG_PID or LOG_NDELAY, LOG_DAEMON);
end;
class procedure TPosixDaemon.LogRaw(const AMessage: string);
begin
syslog(LOG_INFO, AMessage);
end;
class procedure TPosixDaemon.RouteDescriptors;
var
LFileID: Integer;
begin
// Open STDIN
LFileID := __open('/dev/null', O_RDWR);
// Dup STDOUT
dup(LFileID);
// Dup STDERR
dup(LFileID);
end;
class procedure TPosixDaemon.Run(AInterval: Integer);
begin
FRunning := True;
while FRunning do
begin
Sleep(AInterval);
end;
LogInfo('The daemon is finally killed!');
LogClose;
end;
class procedure TPosixDaemon.Setup(ASignalProc: TSignalProc);
begin
FSignalProc := ASignalProc;
LogOpen;
FProcessID := ForkProcess;
KillParent(FProcessID);
DetachTerminal;
FProcessID := ForkProcess;
KillParent(FProcessID);
CatchHandleSignals;
CloseDescriptors;
RouteDescriptors;
UserFileMask(027);
SetRootDirectory('/');
end;
class procedure TPosixDaemon.Stop;
begin
FRunning := False;
end;
class procedure TPosixDaemon.UserFileMask(AMask: Cardinal);
begin
umask(AMask);
end;
class procedure TPosixDaemon.SetRootDirectory(const ADirectory: string);
begin
ChDir(ADirectory);
end;
end.