File: exec_tools.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 (349 lines) | stat: -rw-r--r-- 9,077 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
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
/*
  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 <exec_tools.h>

#include <files_names.h>
#include <files_interfaces.h>
#include <pipes.h>
#include <string_lib.h>
#include <misc_lib.h>
#include <file_lib.h>
#include <generic_agent.h> // CloseLog

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

bool GetExecOutput(const char *command, char **buffer, size_t *buffer_size, ShellType shell, OutputSelect output_select, int *ret_out)
/* Buffer initially contains whole exec string */
{
    FILE *pp;

    if (shell == SHELL_TYPE_USE)
    {
        pp = cf_popen_sh_select(command, "rt", output_select);
    }
    else if (shell == SHELL_TYPE_POWERSHELL)
    {
#ifdef __MINGW32__
        pp = cf_popen_powershell_select(command, "rt", output_select);
#else // !__MINGW32__
        Log(LOG_LEVEL_ERR, "Powershell is only supported on Windows");
        return false;
#endif // __MINGW32__
    }
    else
    {
        pp = cf_popen_select(command, "rt", output_select);
    }

    if (pp == NULL)
    {
        Log(LOG_LEVEL_ERR, "Couldn't open pipe to command '%s'. (cf_popen: %s)", command, GetErrorStr());
        return false;
    }

    size_t offset = 0;
    size_t line_size = CF_EXPANDSIZE;
    size_t attempted_size = 0;
    char *line = xcalloc(1, line_size);

    while (*buffer_size < CF_MAXSIZE)
    {
        ssize_t res = CfReadLine(&line, &line_size, pp);
        if (res == -1)
        {
            if (!feof(pp))
            {
                Log(LOG_LEVEL_ERR, "Unable to read output of command '%s'. (fread: %s)", command, GetErrorStr());
                cf_pclose(pp);
                free(line);
                return false;
            }
            else
            {
                break;
            }
        }

        if ((attempted_size = snprintf(*buffer + offset, *buffer_size - offset, "%s\n", line)) >= *buffer_size - offset)
        {
            *buffer_size += (attempted_size > CF_EXPANDSIZE ? attempted_size : CF_EXPANDSIZE);
            *buffer = xrealloc(*buffer, *buffer_size);
            snprintf(*buffer + offset, *buffer_size - offset, "%s\n", line);
        }

        offset += strlen(line) + 1;
    }

    if (offset > 0)
    {
        if (Chop(*buffer, *buffer_size) == -1)
        {
            Log(LOG_LEVEL_ERR, "Chop was called on a string that seemed to have no terminator");
        }
    }

    Log(LOG_LEVEL_DEBUG, "GetExecOutput got '%s'", *buffer);

    if (ret_out != NULL)
    {
        *ret_out = cf_pclose(pp);
    }
    else
    {
        cf_pclose(pp);
    }

    free(line);
    return true;
}

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

void ActAsDaemon()
{
    int fd;

#ifdef HAVE_SETSID
    if (setsid() == (pid_t) -1)
    {
        Log(LOG_LEVEL_WARNING,
            "Failed to become a session leader while daemonising (setsid: %s)",
            GetErrorStr());
    }
#endif

    CloseNetwork();
    CloseLog();

    fflush(NULL);

    /* Close descriptors 0,1,2 and reopen them with /dev/null. */

    fd = open(NULLFILE, O_RDWR, 0);
    if (fd == -1)
    {
        Log(LOG_LEVEL_WARNING, "Could not open '%s', "
            "stdin/stdout/stderr are still open (open: %s)",
            NULLFILE, GetErrorStr());
    }
    else
    {
        if (dup2(fd, STDIN_FILENO) == -1)
        {
            Log(LOG_LEVEL_WARNING,
                "Could not close stdin while daemonising (dup2: %s)",
                GetErrorStr());
        }

        if (dup2(fd, STDOUT_FILENO) == -1)
        {
            Log(LOG_LEVEL_WARNING,
                "Could not close stdout while daemonising (dup2: %s)",
                GetErrorStr());
        }

        if (dup2(fd, STDERR_FILENO) == -1)
        {
            Log(LOG_LEVEL_WARNING,
                "Could not close stderr while daemonising (dup2: %s)",
                GetErrorStr());
        }

        if (fd > STDERR_FILENO)
        {
            close(fd);
        }
    }

    if (chdir("/"))
    {
        Log(LOG_LEVEL_WARNING,
            "Failed to chdir into '/' directory while daemonising (chdir: %s)",
            GetErrorStr());
    }
}

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

/**
 * Split the command string like "/bin/echo -n Hi!" in two parts -- the
 * executable ("/bin/echo") and the arguments for the executable ("-n Hi!").
 *
 * @param[in]  comm  the whole command to split
 * @param[out] exec  pointer to **a newly allocated** string with the executable
 * @param[out] args  pointer to **a newly allocated** string with the args
 *
 * @note Whitespace between the executable and the arguments is skipped.
 */
void ArgGetExecutableAndArgs(const char *comm, char **exec, char **args)
{
    const char *s = comm;
    while (*s != '\0')
    {
        const char *end = NULL;

        if (isspace((int)*s))        /* Skip whitespace */
        {
            s++;
            continue;
        }

        switch (*s)
        {
        case '"':              /* Look for matching quote */
        case '\'':
        case '`':
        {
            char delim = *(s++);  /* Skip first delimeter */

            end = strchr(s, delim);
            break;
        }
        default:               /* Look for whitespace */
            end = strpbrk(s, " \f\n\r\t\v");
            break;
        }

        if (end == NULL)        /* Delimeter was not found, remaining string is the executable */
        {
            *exec = xstrdup(s);
            *args = NULL;
            return;
        }
        else
        {
            assert(end > s);
            const size_t length = end - s;
            *exec = xstrndup(s, length);

            const char *args_start = end;
            if (*(args_start + 1) != '\0')
            {
                args_start++; /* Skip second delimeter */
                args_start += strspn(args_start, " \f\n\r\t\v"); /* Skip whitespace */
                *args = xstrdup(args_start);
            }
            else
            {
                *args = NULL;
            }
            return;
        }
    }

    /* was not able to parse/split the command */
    *exec = NULL;
    *args = NULL;
    return;
}

#define INITIAL_ARGS 8

char **ArgSplitCommand(const char *comm, const Seq *arglist)
{
    const char *s = comm;

    int argc = 0;
    int argslen = INITIAL_ARGS;
    char **args = xmalloc(argslen * sizeof(char *));

    while (*s != '\0')
    {
        const char *end;
        char *arg;

        if (isspace((int)*s))        /* Skip whitespace */
        {
            s++;
            continue;
        }

        switch (*s)
        {
        case '"':              /* Look for matching quote */
        case '\'':
        case '`':
        {
            char delim = *s++;  /* Skip first delimeter */

            end = strchr(s, delim);
            break;
        }
        default:               /* Look for whitespace */
            end = strpbrk(s, " \f\n\r\t\v");
            break;
        }

        if (end == NULL)        /* Delimeter was not found, remaining string is the argument */
        {
            arg = xstrdup(s);
            s += strlen(arg);
        }
        else
        {
            arg = xstrndup(s, end - s);
            s = end;
            if ((*s == '"') || (*s == '\'') || (*s == '`'))   /* Skip second delimeter */
                s++;
        }

        /* Argument */

        if (argc == argslen)
        {
            argslen *= 2;
            args = xrealloc(args, argslen * sizeof(char *));
        }

        args[argc++] = arg;
    }

    size_t extra = (arglist == NULL) ? 0 : SeqLength(arglist);
    if (argc + extra + 1 /* NULL */ > argslen)
    {
        args = xrealloc(args, (argc + extra + 1) * sizeof(char *));
    }

    for (size_t i = 0; i < extra; i++) {
        args[argc++] = xstrdup(SeqAt(arglist, i));
    }
    args[argc] = NULL;

    return args;
}

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

void ArgFree(char **args)
{
    if (args != NULL)
    {
        for (char **arg = args; *arg; ++arg)
        {
            free(*arg);
        }
        free(args);
    }
}