summaryrefslogtreecommitdiffstats
path: root/src/detection/command/command.c
blob: 28c6f4b72727a6ffbad73794d78cf5290ee156ea (plain) (blame)
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
#include "detection/command/command.h"
#include "common/processing.h"
#include "common/FFstrbuf.h"

typedef struct FFCommandResultBundle {
    FFProcessHandle handle;
    const char* error;
} FFCommandResultBundle;

// FIFO, non-thread-safe list of running commands
static FFlist commandQueue;

static const char* spawnProcess(FFCommandOptions* options, FFProcessHandle* handle) {
    if (options->text.length == 0) {
        return "No command text specified";
    }

    return ffProcessSpawn(options->param.length ? (char* const[]) {
                                                      options->shell.chars,
                                                      options->param.chars,
                                                      options->text.chars,
                                                      NULL }
                                                : (char* const[]) { options->shell.chars, options->text.chars, NULL },
        options->useStdErr,
        handle);
}

bool ffPrepareCommand(FFCommandOptions* options) {
    if (!options->parallel) {
        return false;
    }

    FFCommandResultBundle* bundle = FF_LIST_ADD(FFCommandResultBundle, commandQueue);
    bundle->error = spawnProcess(options, &bundle->handle);

    return true;
}

const char* ffDetectCommand(FFCommandOptions* options, FFstrbuf* result) {
    FFCommandResultBundle bundle = {};
    if (!options->parallel) {
        bundle.error = spawnProcess(options, &bundle.handle);
    } else if (!FF_LIST_SHIFT(commandQueue, &bundle)) {
        return "[BUG] command queue is empty";
    }

    if (bundle.error) {
        return bundle.error;
    }

    bundle.error = ffProcessReadOutput(&bundle.handle, result);
    if (bundle.error) {
        return bundle.error;
    }

    ffStrbufTrimRightSpace(result);
    return NULL;
}