File: signals.c

package info (click to toggle)
cfengine3 3.24.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 37,552 kB
  • sloc: ansic: 163,161; sh: 10,296; python: 2,950; makefile: 1,744; lex: 784; yacc: 633; perl: 211; pascal: 157; xml: 21; sed: 13
file content (252 lines) | stat: -rw-r--r-- 7,318 bytes parent folder | download | duplicates (2)
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
/*
  Copyright 2024 Northern.tech AS

  This file is part of CFEngine 3 - written and maintained by Northern.tech AS.

  This program is free software; you can redistribute it and/or modify it
  under the terms of the GNU General Public License as published by the
  Free Software Foundation; version 3.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA

  To the extent this program is licensed as part of the Enterprise
  versions of CFEngine, the applicable Commercial Open Source License
  (COSL) may apply to this file if you as a licensee so wish it. See
  included file COSL.txt.
*/

#include <signals.h>
#include <cleanup.h>
#include <known_dirs.h>         /* GetStateDir() */
#include <file_lib.h>           /* FILE_SEPARATOR */
#include <mod_custom.h>         /* TerminateCustomPromises */

static bool PENDING_TERMINATION = false; /* GLOBAL_X */

static bool RELOAD_CONFIG = false; /* GLOBAL_X */
/********************************************************************/

bool IsPendingTermination(void)
{
    return PENDING_TERMINATION;
}

bool ReloadConfigRequested(void)
{
    return RELOAD_CONFIG;
}

void ClearRequestReloadConfig()
{
    RELOAD_CONFIG = false;
}

void RequestReloadConfig()
{
    RELOAD_CONFIG = true;
}

/********************************************************************/

static int SIGNAL_PIPE[2] = { -1, -1 }; /* GLOBAL_C */

static void CloseSignalPipe(void)
{
    int c = 2;
    while (c > 0)
    {
        c--;
        if (SIGNAL_PIPE[c] >= 0)
        {
            close(SIGNAL_PIPE[c]);
            SIGNAL_PIPE[c] = -1;
        }
    }
}

/**
 * Make a pipe that can be used to flag that a signal has arrived.
 * Using a pipe avoids race conditions, since it saves its values until emptied.
 * Use GetSignalPipe() to get the pipe.
 * Note that we use a real socket as the pipe, because Windows only supports
 * using select() with real sockets. This means also using send() and recv()
 * instead of write() and read().
 */
void MakeSignalPipe(void)
{
    if (socketpair(AF_UNIX, SOCK_STREAM, 0, SIGNAL_PIPE) != 0)
    {
        Log(LOG_LEVEL_CRIT, "Could not create internal communication pipe. Cannot continue. (socketpair: '%s')",
            GetErrorStr());
        DoCleanupAndExit(EXIT_FAILURE);
    }

    RegisterCleanupFunction(&CloseSignalPipe);

    for (int c = 0; c < 2; c++)
    {
#ifdef __MINGW32__
        u_long enable = 1;
        int ret = ioctlsocket(SIGNAL_PIPE[c], FIONBIO, &enable);
#define CNTLNAME "ioctlsocket"
#else /* Unix: */
        int ret = fcntl(SIGNAL_PIPE[c], F_SETFL, O_NONBLOCK);
#define CNTLNAME "fcntl"
#endif /* __MINGW32__ */

        if (ret != 0)
        {
            Log(LOG_LEVEL_CRIT,
                "Could not unblock internal communication pipe. "
                "Cannot continue. (" CNTLNAME ": '%s')",
                GetErrorStr());
            DoCleanupAndExit(EXIT_FAILURE);
        }
#undef CNTLNAME
    }
}

/**
 * Gets the signal pipe, which is non-blocking.
 * Each byte read corresponds to one arrived signal.
 * Note: Use recv() to read from the pipe, not read().
 */
int GetSignalPipe(void)
{
    return SIGNAL_PIPE[0];
}

static void SignalNotify(int signum)
{
    unsigned char sig = (unsigned char)signum;
    if (SIGNAL_PIPE[1] >= 0)
    {
        // send() is async-safe, according to POSIX.
        if (send(SIGNAL_PIPE[1], &sig, 1, 0) < 0)
        {
            // These signal contention. Everything else is an error.
            if (errno != EAGAIN
#ifndef __MINGW32__
                && errno != EWOULDBLOCK
#endif
                )
            {
                // This is not async safe, but if we get in here there's something really weird
                // going on.
                Log(LOG_LEVEL_CRIT, "Could not write to signal pipe. Unsafe to continue. (write: '%s')",
                    GetErrorStr());
                _exit(EXIT_FAILURE);
            }
        }
    }
}

void HandleSignalsForAgent(int signum)
{
    switch (signum)
    {
    case SIGTERM:
    case SIGINT:
        /* TODO don't exit from the signal handler, just set a flag. Reason is
         * that all the cleanup() hooks we register are not reentrant. */
        TerminateCustomPromises();
        DoCleanupAndExit(0);
    case SIGBUS:
        /* SIGBUS almost certainly means a violation of mmap() area boundaries
         * or some mis-aligned memory access. IOW, an LMDB corruption. */
        {
            char filename[PATH_MAX] = { 0 }; /* trying to avoid memory allocation */
            xsnprintf(filename, PATH_MAX, "%s%c%s",
                      GetStateDir(), FILE_SEPARATOR, CF_DB_REPAIR_TRIGGER);
            int fd = open(filename, O_CREAT|O_RDWR, CF_PERMS_DEFAULT);
            if (fd != -1)
            {
                close(fd);
            }

            /* avoid calling complex logging functions */
            fprintf(stdout, "process killed by SIGBUS\n");

            /* else: we tried, nothing more to do in the limited environment of a
             * signal handler */
            _exit(1);
        }
        break;
    case SIGUSR1:
        LogSetGlobalLevel(LOG_LEVEL_DEBUG);
        break;
    case SIGUSR2:
        LogSetGlobalLevel(LOG_LEVEL_NOTICE);
        break;
    default:
        /* No action */
        break;
    }

    SignalNotify(signum);

/* Reset the signal handler */
    signal(signum, HandleSignalsForAgent);
}

/********************************************************************/

void HandleSignalsForDaemon(int signum)
{
    switch (signum)
    {
    case SIGTERM:
    case SIGINT:
    case SIGSEGV:
    case SIGKILL:
        PENDING_TERMINATION = true;
        break;
    case SIGBUS:
        /* SIGBUS almost certainly means a violation of mmap() area boundaries
         * or some mis-aligned memory access. IOW, an LMDB corruption. */
        {
            char filename[PATH_MAX] = { 0 }; /* trying to avoid memory allocation */
            xsnprintf(filename, PATH_MAX, "%s%c%s",
                      GetStateDir(), FILE_SEPARATOR, CF_DB_REPAIR_TRIGGER);
            int fd = open(filename, O_CREAT|O_RDWR, CF_PERMS_DEFAULT);
            if (fd != -1)
            {
                close(fd);
            }

            /* avoid calling complex logging functions */
            fprintf(stdout, "process killed by SIGBUS\n");

            /* else: we tried, nothing more to do in the limited environment of a
             * signal handler */
            _exit(1);
        }
        break;
    case SIGUSR1:
        LogSetGlobalLevel(LOG_LEVEL_DEBUG);
        break;
    case SIGUSR2:
        LogSetGlobalLevel(LOG_LEVEL_NOTICE);
        break;
    case SIGHUP:
        RELOAD_CONFIG = true;
        break;
    case SIGPIPE:
    default:
        /* No action */
        break;
    }

    /* Notify processes that use the signal pipe (cf-serverd). */
    SignalNotify(signum);

    /* Reset the signal handler. */
    signal(signum, HandleSignalsForDaemon);
}