summaryrefslogtreecommitdiff
path: root/website-kernel/fs/fs_cpio.c
blob: bbab632d4d805240b551536c30db22f5597c06a1 (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
#include <fs/cpio.h>
#include <sys.h>
#include <int.h>
#include <log.h>

static inline int strcmp(const char *str1, const char* str2) {
    while (*str1 && (*str1 == *str2)) {
        ++str1;
        ++str2;
    }
    return *(const unsigned char *)str1 - *(const unsigned char *)str2;
}

static uint32_t parse_hex(const char *p)
{
    uint32_t value = 0;

    for (int i = 0; i < 8; i++) {
        char c = p[i];
        value <<= 4;

        if (c >= '0' && c <= '9')
            value |= c - '0';
        else if (c >= 'A' && c <= 'F')
            value |= c - 'A' + 10;
        else if (c >= 'a' && c <= 'f')
            value |= c - 'a' + 10;
    }
    return value;
}

void *cpio_get_file(void *archive, size_t size, const char *filename) {
    const uint8_t *p = (uint8_t *)archive;
    const uint8_t *end = archive + size;

    while (p + CPIO_HEADER_LEN <= end) {
        const struct cpio_newc_hdr *hdr =
            (const struct cpio_newc_hdr *)p;

        if (memcmp(hdr->magic, "070701", 6) &&
            memcmp(hdr->magic, "070702", 6)) {
            printk("Error parsing cpio: bad magic number!\n");
            return NULL;
        }

        uint32_t namesize = parse_hex(hdr->namesize);
        uint32_t filesize = parse_hex(hdr->filesize);

        p += CPIO_HEADER_LEN;

        if (p + namesize > end) {
            printk("Error parsing cpio: truncated filename\n");
            return NULL;
        }

        const char *name = (const char *)p;

        if (strcmp(name, "TRAILER!!!") == 0)
            return NULL;

        p += namesize;

        if (p + filesize > end) {
            printk("Error parsing cpio: truncated file\n");
            return NULL;
        }

        if (strcmp(name, filename) == 0) {
            return (void*)p;
        }

        p += filesize;
    }
    return NULL;
}