File: process.c

package info (click to toggle)
prayer 1.3.5-dfsg1-8
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 6,596 kB
  • sloc: ansic: 43,163; makefile: 817; sh: 445; perl: 166
file content (388 lines) | stat: -rw-r--r-- 10,656 bytes parent folder | download | duplicates (6)
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
/* $Cambridge: hermes/src/prayer/lib/process.c,v 1.3 2008/09/16 09:59:57 dpc22 Exp $ */
/************************************************
 *    Prayer - a Webmail Interface              *
 ************************************************/

/* Copyright (c) University of Cambridge 2000 - 2008 */
/* See the file NOTICE for conditions of use and distribution. */

#include "lib.h"

#define MAXLENGTH        (8192)

/* Class for communicating with subsiduary process using Pseudo Terminal */

/* process_clear() *******************************************************
 *
 * Clear process state
 ************************************************************************/

void process_clear(struct process *process)
{
    process->childpid = 0;
    process->stream = NIL;
}

/* ====================================================================== */

/* process_makeenv() *****************************************************
 *
 * Utility routine for setting up environment in child process.
 ************************************************************************/

static
char *process_makeenv(char *key, char *value)
{
    char *result;

    if ((result = malloc(strlen(key) + strlen(value) + 2)) == NIL)
        log_fatal("Out of memory");

    sprintf(result, "%s=%s", key, value);
    return (result);
}

/* process_exec() ********************************************************
 *
 * exec new process.
 ************************************************************************/

BOOL process_exec(char *cmdline)
{
    struct passwd *pwd;
    char *path, *s;
    int argc;
    char **argv;
    char *env[6];

    /* Set up environment array for child process */
    if ((pwd = getpwuid(getuid())) == NIL)
        log_fatal("getpwuid() failed");

    env[0] = process_makeenv("HOME", pwd->pw_dir);
    env[1] = process_makeenv("LOGNAME", pwd->pw_name);
    env[2] = process_makeenv("USER", pwd->pw_name);
    env[3] = process_makeenv("PATH", "/bin:/usr/bin:/opt/local/bin");
    env[4] = process_makeenv("SHELL", "/bin/false");
    env[5] = NIL;

    /* Work out correct size for the argv array */
    argc = 0;
    s = cmdline;
    while (*s) {
        if ((*s == ' ') || (*s == '\t')) {
            argc++;
            while ((*s == ' ') || (*s == '\t'))
                s++;
        } else
            s++;
    }

    /* Allocate the argv array */
    if ((argv = malloc((argc + 1) * sizeof(char *))) == NIL) {
        log_fatal("process_exec(): Out of memory");
        /* NOTREACHED */
        exit(1);
    }

    /* Set up argv array */
    argv[0] = path = strdup(cmdline);
    argc = 0;

    s = path;
    while (*s) {
        if ((*s == ' ') || (*s == '\t')) {
            *s++ = '\0';
            while ((*s == ' ') || (*s == '\t'))
                s++;
            if (*s)
                argv[++argc] = s;
        } else
            s++;
    }
    argv[argc + 1] = NIL;

    /* Caculate argv[0] if full pathname was provided */
    if (strrchr(argv[0], '/'))
        argv[0] = strrchr(path, '/') + 1;

    execve(path, argv, env);
    log_fatal("Failed to execve() passwd program");
    /* NOTREACHED */
    exit(1);
}

/* ====================================================================== */

/* process_start() *******************************************************
 *
 * Start up subsiduary process for communication
 *    process:  Wrapper structure for state
 *    cmdline:  Program that we are about to run
 *    use_pty:  Run program inside a Pseudo terminal
 *       argv:  argv array to pass to child.
 *
 * Returns: T if subprocess started successfully. NIL otherwise.
 ************************************************************************/

BOOL
process_start(struct process *process, char *cmdline, BOOL use_pty,
              unsigned long timeout)
{
    int childpid;
    int masterfd;

    if (use_pty) {
        if (!os_run_pty(cmdline, &masterfd, &childpid)) {
            log_misc("Failed to open pseudoterminal");
            return (NIL);
        }
    } else {
        if (!os_run(cmdline, &masterfd, &childpid)) {
            log_misc("Failed to open pseudoterminal");
            return (NIL);
        }
    }

    process->use_pty = use_pty;
    process->childpid = childpid;
    if (!(process->stream = iostream_create(NIL, masterfd, 0)))
        return (NIL);

    iostream_set_timeout(process->stream, timeout);
    return (T);
}

/* ====================================================================== */

/* process_stop() *********************************************************
 *
 * Stop a running process: shuts down iostream connection and waits for
 * process to finish.
 *************************************************************************/

BOOL process_stop(struct process * process)
{
    int status;

    if (process->childpid == 0)
        return (NIL);

    if (process->stream)
        iostream_close(process->stream);

    waitpid(process->childpid, &status, 0);

    return (T);
}

/* ====================================================================== */

/* process_expect_string() ***********************************************
 *
 * Match string on following line of output from child process.
 *
 * Returns:
 *    string matched sucessfully => NIL
 *    Otherwise                  => Line from child as error condition
 ************************************************************************/

static char *process_expect_string(struct process *process, char *string,
                                   char *warning)
{
    unsigned long len = strlen(string);
    unsigned long count = 0;
    struct iostream *stream = process->stream;
    char c;
    static char buffer[MAXLENGTH];

    buffer[0] = '\0';

    while ((c = iogetc(stream)) != EOF) {
        if (c == '\r')
            continue;

        if (count == MAXLENGTH)
            return ("Line from child process too long");

        buffer[count++] = c;
        if ((count >= len)
            && !strncmp(buffer + (count - len), string, len))
            return (NIL);

        if (c == '\n') {
            if (warning && !strncmp(buffer, warning, strlen(warning))) {
                count = 0;      /* Ignore warning lines */
                buffer[0] = '\0';
            } else {
                buffer[count - 1] = '\0';       /* Return line from child as error */
                return (buffer);
            }
        }
    }
    return ("End of file or timeout waiting for input");
}

/* process_read_line() ***************************************************
 *
 * Fetch a line from child process
 *  process:
 *      buf: Target buffer (if defined)
 *     blen: Length of target buffer (if defined)
 * 
 * Returns: T => got line. NIL => EOF.
 ************************************************************************/

BOOL
process_read_line(struct process * process, char *buf, unsigned long blen)
{
    struct iostream *stream = process->stream;
    char c;
    unsigned long i = 0;

    if (blen > 0)
        blen--;                 /* Leave space for trailing '\0' */

    while ((c = iogetc(stream)) != EOF) {
        if (c == '\r')
            continue;

        if (c == '\n') {
            if (buf && (i < blen))
                buf[i] = '\0';
            return (T);
        }

        if (buf && (i < blen))
            buf[i++] = c;
    }
    return (NIL);
}

/* process_get_token() **************************************************
 *
 * Isolate next token in string
 *    sp: Ptr to current string location
 *        (updated to point to following token)
 *
 * Returns: Ptr to next token, NIL if none.
 ***********************************************************************/

static char *process_get_token(char **sp)
{
    char *s = *sp, *result;

    if (!(s = string_next_token(sp)))
        return (NIL);

    if (*s == '"') {
        /* Deal with quoted strings */
        result = s + 1;
        s += 2;

        while (*s && (*s != '"'))
            s++;

        if (*s == '\0')
            return (NIL);

        *s++ = '\0';
        *sp = s;
        return (result);
    }

    /* Record position of this token */
    result = s;

    /* Find next whitespace character or end of string */
    while ((*s) && (*s != ' ') && (*s != '\t'))
        s++;

    /* Tie off the string unless \0 already reached */
    if (*s) {
        *s++ = '\0';

        while ((*s == ' ') || (*s == '\t'))
            s++;
    }

    /* Record position of first non-whitespace character for next caller */
    *sp = s;

    return (result);
}

/* ====================================================================== */

/* process_run_script() **************************************************
 *
 * Run script against process
 *
 * Returns:
 *  NIL   => script matched successfully
 *  ""    => unexpected EOF
 *  Other => Last line of output from child as an error condition
 ************************************************************************/

char *process_run_script(struct process *process,
                         struct pool *pool, struct assoc *h,
                         char *script, char *result,
                         unsigned long result_length)
{
    char *type, *value, *ret;
    char *warning = NIL;
    struct iostream *stream = process->stream;

    while (*script) {
        if (!(type = string_get_token(&script)))
            return (NIL);

        if (!strcasecmp(type, "readline")) {
            if (!process_read_line(process, NIL, 0L))
                return ("");
            continue;
        }

        if (!strcasecmp(type, "result")) {
            if (!process_read_line(process, result, result_length))
                return ("");
            return (NIL);
        }

        if (!(value = process_get_token(&script)))
            return (NIL);

        value = string_expand(pool, h, value);

        if (!strcasecmp(type, "warning")) {
            warning = value;
            continue;
        }

        if (!strcasecmp(type, "expect")) {
            if ((ret = process_expect_string(process, value, warning)))
                return (ret);
            continue;
        }

        if (!strcasecmp(type, "sendline")) {
            ioprintf(stream, "%s\n", value);
            ioflush(stream);

            if (process->use_pty && !process_read_line(process, NIL, 0L))
                return ("");
            continue;
        }

        if (!strcasecmp(type, "send")) {
            ioputs(stream, value);
            ioflush(stream);
            continue;
        }

        log_panic("Unexpected command in script: %s %s", type, value);
        return ("Internal server error");
    }
    /* Script finished sucessfully */
    return (NIL);
}