//
//  vnode.m
//  Cyanide
//
//  Created by seo on 3/25/26.
//

#import "vnode.h"
#import "krw.h"
#import "kutils.h"
#import "offsets.h"
#import "xpaci.h"
#import "apfs_fsnode.h"
#import "../LogTextView.h"

#import <stdlib.h>
#import <unistd.h>
#import <fcntl.h>
#import <stdbool.h>
#import <string.h>
#import <Foundation/Foundation.h>
#import <sys/stat.h>

uint64_t get_vnode_for_path_by_chdir(const char *path) {
    if (access(path, F_OK) == -1) {
        return -1;
    }
    if (chdir(path) == -1) { return -1; }
    
    uint64_t fd_cdir_vp = kread64(proc_self() + off_proc_p_fd + off_filedesc_fd_cdir);
    chdir("/");
    return fd_cdir_vp;
}

uint64_t get_vnode_for_path_by_open(const char *path) {
    int fd = open(path, O_RDONLY);
    if (fd == -1) return -1;
    
    uint64_t fileprocPtrArr = kread64(proc_self() + off_proc_p_fd + off_filedesc_fd_ofiles);
    fileprocPtrArr = xpaci(fileprocPtrArr);
    uint64_t fileproc = kread64(fileprocPtrArr + (8 * fd));
    uint64_t fp_glob = kread64(fileproc + off_fileproc_fp_glob);
    fp_glob = xpaci(fp_glob);
    uint64_t vnode = kread64(fp_glob + off_fileglob_fg_data);
    vnode = xpaci(vnode);
    
    close(fd);
    return vnode;
}

uint64_t get_vnode_by_fd(int fd) {
    uint64_t fileprocPtrArr = kread64(proc_self() + off_proc_p_fd + off_filedesc_fd_ofiles);
    fileprocPtrArr = xpaci(fileprocPtrArr);
    uint64_t fileproc = kread64(fileprocPtrArr + (8 * fd));
    uint64_t fp_glob = kread64(fileproc + off_fileproc_fp_glob);
    fp_glob = xpaci(fp_glob);
    uint64_t vnode = kread64(fp_glob + off_fileglob_fg_data);
    vnode = xpaci(vnode);
    return vnode;
}

uint64_t get_rootvnode(void) {
    uint64_t launchd_proc = proc_find(1);
    uint64_t launchd_vnode = kread64(launchd_proc + off_proc_p_textvp);
    launchd_vnode = xpaci(launchd_vnode);
    
    uint64_t sbin_vnode = kread64(launchd_vnode + off_vnode_v_parent);
    sbin_vnode = xpaci(sbin_vnode);
    
    uint64_t root_vnode = kread64(sbin_vnode + off_vnode_v_parent);
    root_vnode = xpaci(root_vnode);
    
    return root_vnode;
}

char vp_name[256];
char* vnode_get_v_name(uint64_t vnode) {
    memset(vp_name, 0, 256);
    uint64_t vp_nameptr = kread64(vnode + off_vnode_v_name);
    kreadbuf(vp_nameptr, &vp_name, 256);
    return vp_name;
}

uint64_t vnode_redirect_folder(const char *to, const char *from) {
    uint64_t to_vnode = get_vnode_for_path_by_chdir(to);
    uint64_t orig_to_v_data = kread64(to_vnode + off_vnode_v_data);
    uint64_t from_vnode = get_vnode_for_path_by_chdir(from);
    uint64_t from_v_data = kread64(from_vnode + off_vnode_v_data);
    
    kwrite64(to_vnode + off_vnode_v_data, from_v_data);
    
    return orig_to_v_data;
}

bool vnode_unredirect_folder(const char *folder, uint64_t orig_to_v_data) {
    uint64_t vnode = get_vnode_for_path_by_chdir(folder);
    if (vnode == -1) return false;
    
    kwrite64(vnode + off_vnode_v_data, orig_to_v_data);
    
    return true;
}

bool vnode_redirect_file(const char *to, const char *from, uint64_t* orig_to_vnode, uint64_t* orig_to_v_data) {
    uint64_t to_vnode = get_vnode_for_path_by_open(to);
    if(to_vnode == -1) {
        NSString *to_dir = [[NSString stringWithUTF8String:to] stringByDeletingLastPathComponent];
        NSString *to_file = [[NSString stringWithUTF8String:to] lastPathComponent];
        uint64_t to_dir_vnode = get_vnode_for_path_by_chdir(to_dir.UTF8String);
        to_vnode = vnode_get_child_vnode(to_dir_vnode, to_file.UTF8String, 0);
        if(to_vnode == -1) {
            printf("[-] Couldn't find file (to): %s", to);
            return false;
        }
    }
    
    uint64_t from_vnode = get_vnode_for_path_by_open(from);
    if(from_vnode == -1) {
        NSString *from_dir = [[NSString stringWithUTF8String:from] stringByDeletingLastPathComponent];
        NSString *from_file = [[NSString stringWithUTF8String:from] lastPathComponent];
        uint64_t from_dir_vnode = get_vnode_for_path_by_chdir(from_dir.UTF8String);
        from_vnode = vnode_get_child_vnode(from_dir_vnode, from_file.UTF8String, 0);
        if(from_vnode == 0) {
            printf("[-] Couldn't find file (from): %s", from);
            return false;
        }
    }
    
    *orig_to_vnode = to_vnode;
    *orig_to_v_data = kread64(to_vnode + off_vnode_v_data);
    uint64_t from_v_data = kread64(from_vnode + off_vnode_v_data);
    kwrite64(to_vnode + off_vnode_v_data, from_v_data);
    
    return true;
}

bool vnode_unredirect_file(uint64_t orig_to_vnode, uint64_t orig_to_v_data) {
    kwrite64(orig_to_vnode + off_vnode_v_data, orig_to_v_data);
    
    return true;
}
    
uint64_t vnode_get_child_vnode(uint64_t vnode, const char* child_filename, uint64_t blacklist_vdata) {
    if(!is_kaddr_valid(vnode))  return -1;
    uint64_t vp_namecache = kread64(vnode + off_vnode_v_ncchildren_tqh_first);
    if(vp_namecache == 0)   return -1;

    for (int i = 0; i < 4096; i++) {
        if(!is_kaddr_valid(vp_namecache))   break;
        vnode = kread64(vp_namecache + off_namecache_nc_vp);

        if(vnode == 0)  break;
        char* vp_name = vnode_get_v_name(vnode);

        if(strcmp(vp_name, child_filename) == 0 && kread64(vnode + off_vnode_v_data) != blacklist_vdata) {
            return vnode;
        }
        vp_namecache = kread64(vp_namecache + off_namecache_nc_child_tqe_next);
    }

    return -1;
}

// Like vnode_get_child_vnode, but skips negative/unlinked namecache entries
// (nc_vp == 0) instead of stopping at them, and validates every pointer before
// dereferencing it. Used by the from-root namecache walk, where hitting an
// invalid pointer must fail gracefully, never fault.
static uint64_t vnode_find_child_safe(uint64_t dirvnode, const char *name, uint64_t blacklist_vdata) {
    if(!is_kaddr_valid(dirvnode))   return -1;
    uint64_t nc = kread64(dirvnode + off_vnode_v_ncchildren_tqh_first);
    for (int i = 0; i < 4096 && is_kaddr_valid(nc); i++) {
        uint64_t vp = kread64(nc + off_namecache_nc_vp);
        if (is_kaddr_valid(vp)) {               // skip negative entries, keep walking
            char *nm = vnode_get_v_name(vp);
            if (strcmp(nm, name) == 0 &&
                kread64(vp + off_vnode_v_data) != blacklist_vdata) {
                return vp;
            }
        }
        nc = kread64(nc + off_namecache_nc_child_tqe_next);
    }
    return -1;
}

// List the names of a directory vnode's cached children (negative/unlinked
// entries skipped). Returns the count written (<= maxNames).
int vnode_list_child_names(uint64_t dirvnode, char names[][256], int maxNames) {
    if (!is_kaddr_valid(dirvnode) || !names || maxNames <= 0) return 0;
    int n = 0;
    uint64_t nc = kread64(dirvnode + off_vnode_v_ncchildren_tqh_first);
    for (int i = 0; i < 4096 && is_kaddr_valid(nc) && n < maxNames; i++) {
        uint64_t vp = kread64(nc + off_namecache_nc_vp);
        if (is_kaddr_valid(vp)) {
            char *nm = vnode_get_v_name(vp);
            if (nm[0]) {
                strncpy(names[n], nm, 255);
                names[n][255] = '\0';
                n++;
            }
        }
        nc = kread64(nc + off_namecache_nc_child_tqe_next);
    }
    return n;
}

// Resolve an absolute path to its vnode by walking the kernel namecache from
// the root vnode, one component at a time. Needs NO userspace access to the
// path, so it works where the sandbox denies chdir()/open() -- as long as a
// prior lookup of the path (even a denied one, e.g. access()) has populated
// the namecache, since the MAC denial happens after namei caches each
// component. blacklist_vdata is only applied to the final component (same
// semantics as vnode_get_child_vnode). Returns the vnode, or -1 on failure.
uint64_t get_vnode_for_path_by_namecache(const char *path, uint64_t blacklist_vdata) {
    if (!path || path[0] != '/')    return -1;
    uint64_t cur = get_rootvnode();
    if (!is_kaddr_valid(cur)) {
        printf("[VNODE] namecache walk: root vnode unavailable\n");
        return -1;
    }

    const char *p = path;
    while (*p == '/') p++;
    while (*p) {
        const char *slash = strchr(p, '/');
        size_t len = slash ? (size_t)(slash - p) : strlen(p);
        if (len == 0 || len >= 256) { return -1; }
        bool last = (slash == NULL);
        char comp[256];
        memcpy(comp, p, len);
        comp[len] = '\0';

        uint64_t next = vnode_find_child_safe(cur, comp, last ? blacklist_vdata : 0);
        if (!is_kaddr_valid(next)) {
            printf("[VNODE] namecache walk: component '%s' not cached (path: %s)\n", comp, path);
            return -1;
        }
        cur = next;

        if (!slash) break;
        p = slash + 1;
        while (*p == '/') p++;
    }
    return cur;
}

uint64_t vnode_fsnode(uint64_t vp) {
    return kread64(vp + off_vnode_v_data);
}

uint32_t apfs_fsnode_get_uid(uint64_t fs_node) {
    return kread32(fs_node + offsetof(struct apfs_fsnode, uid));
}

uint32_t apfs_fsnode_get_gid(uint64_t fs_node) {
    return kread32(fs_node + offsetof(struct apfs_fsnode, gid));
}

uint16_t apfs_fsnode_get_mode(uint64_t fs_node) {
    return kread16(fs_node + offsetof(struct apfs_fsnode, mode));
}

// similar as chown uid
void apfs_fsnode_set_uid(uint64_t fs_node, uint32_t uid) {
    kwrite32(fs_node + offsetof(struct apfs_fsnode, uid), uid);
}

// similar as chown gid
void apfs_fsnode_set_gid(uint64_t fs_node, uint32_t gid) {
    kwrite32(fs_node + offsetof(struct apfs_fsnode, gid), gid);
}

// similar as chmod
void apfs_fsnode_set_mode(uint64_t fs_node, uint16_t mode) {
    kwrite16(fs_node + offsetof(struct apfs_fsnode, mode), mode);
}

// remind that only work on file which located in apfs disk
// example: vnode_apfs_chown("/var/mobile/test", 0, 0); - make owner/group to root
int vnode_apfs_chown(const char* filename, uid_t uid, gid_t gid) {
    uint64_t vnode = get_vnode_for_path_by_open(filename);
    if(vnode == -1) {
        printf("[-] Unable to get vnode, path: %s", filename);
        return -1;
    }
    
    uint64_t fs_node = kread64(vnode + off_vnode_v_data);
    apfs_fsnode_set_uid(fs_node, uid);
    apfs_fsnode_set_gid(fs_node, gid);
    
    sync(); sync(); sync(); sync(); sync(); sync();
    
    struct stat file_stat;
    if(stat(filename, &file_stat) != 0) {
        printf("[-] stat failed at path: %s\n", filename);
        return -1;
    }
    
    if(file_stat.st_uid != uid || file_stat.st_gid != gid) {
        printf("[-] %s failed...\n", __FUNCTION__);
        printf("[-] %s UID: %d\n", filename, file_stat.st_uid);
        printf("[-] %s GID: %d\n", filename, file_stat.st_gid);
        return -1;
    }

    return 0;
}

// remind that only work on file which located in apfs disk
// example: vnode_apfs_chmod("/var/mobile/test", 0100755); - make executable
int vnode_apfs_chmod(const char* filename, mode_t mode) {
    // APFS stores the raw mode, not just the permission bits. Passing 0755
    // here turns a directory into a typeless inode; every caller must include
    // S_IFDIR/S_IFREG. Refuse it before the write. Review P1.
    if ((mode & S_IFMT) == 0) {
        printf("[-] %s refusing typeless mode %#o for %s\n",
               __FUNCTION__, (unsigned)mode, filename ?: "(null)");
        return -1;
    }
    uint64_t vnode = get_vnode_for_path_by_open(filename);
    if(vnode == -1) {
        printf("[-] Unable to get vnode, path: %s", filename);
        return -1;
    }
    
    uint64_t fs_node = kread64(vnode + off_vnode_v_data);
    apfs_fsnode_set_mode(fs_node, mode);
    
    sync(); sync(); sync(); sync(); sync(); sync();
    
    struct stat file_stat;
    if(stat(filename, &file_stat) != 0) {
        printf("[-] stat failed at path: %s\n", filename);
        return -1;
    }
    
    if(file_stat.st_mode != mode) {
        printf("[-] %s failed...\n", __FUNCTION__);
        printf("[-] %s mode: %o\n", filename, file_stat.st_mode);
        return -1;
    }
    
    return 0;
}
