aboutsummaryrefslogtreecommitdiff
path: root/src/jail.c
blob: cf6dfc04557183d22840a18190a823cf4737cca8 (plain)
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
#include <stdio.h>
#include <stdlib.h>
#include <sched.h>
#include <signal.h>
#include <assert.h>

#include "jail.h"
#include "log.h"

static int jail_daemonfn(jail_ctx *ctx);
static int jail_childfn(void *arg);


void jail_init(jail_ctx **ctx, size_t stacksize)
{
    assert(ctx);
    if (stacksize > BUFSIZ)
        stacksize = BUFSIZ;
    if (!*ctx)
        *ctx = calloc(1, sizeof(**ctx));
    assert(*ctx);

    (*ctx)->stacksize = stacksize;
    (*ctx)->stack_ptr = calloc(1, (*ctx)->stacksize);
    (*ctx)->stack_beg =
        (unsigned char *) (*ctx)->stack_ptr
            + (*ctx)->stacksize;
}

void jail_free(jail_ctx **ctx)
{
    free((*ctx)->stack_ptr);
    free(*ctx);
    *ctx = NULL;
}

int jail_daemonize(jail_ctx *ctx)
{
    assert(ctx);
    ctx->jail_pid = fork();

    switch (ctx->jail_pid) {
        case -1:
            W_STRERR("Jail daemonize");
            return 1;
        case 0:
            N("%s", "Jail daemon mainloop");
            jail_daemonfn(ctx);
            break;
    }
    D2("Jail daemon pid: %d", ctx->jail_pid);

    return 0;
}

static int jail_daemonfn(jail_ctx *ctx)
{
    int clone_flags = CLONE_NEWUTS|CLONE_NEWPID|CLONE_NEWIPC|
        CLONE_NEWNS|CLONE_NEWNET;

    assert(ctx);

    while (1) {
        ctx->jail_pid = clone(jail_childfn, ctx->stack_beg,
            SIGCHLD|clone_flags, ctx);
        sleep(1);
        printf("---\n");
    }

    exit(EXIT_SUCCESS);
}

static int jail_childfn(void *arg)
{
    printf("----> CHILD FN <----\n");
    FILE *log = fopen("./test.log", "wb");
    fprintf(log, "---> CHILD FN <----\n");
    sleep(200);
    return 0;
}