summaryrefslogtreecommitdiff
path: root/src/main.zig
blob: b9d9e88ed945c41212e8c802cb7e1d6aa84a1d3d (plain) (blame)
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
const is_debug = builtin.mode == .Debug;

const help =
    \\-h, --help           Display this help and exit.
    \\-r, --relay <str>    A relay message to send.
    \\-d, --dest <str>     An IPv4 or <= 4 ASCII byte string.
    \\-c, --connect <str>  A connection message to send.
    \\
;

const Option = enum { help, relay, dest, connect };
const to_option: StaticStringMap(Option) = .initComptime(.{
    .{ "-h", .help },
    .{ "--help", .help },
    .{ "-r", .relay },
    .{ "--relay", .relay },
    .{ "-d", .dest },
    .{ "--dest", .dest },
    .{ "-c", .connect },
    .{ "--connect", .connect },
});

pub fn main(init: std.process.Init) !void {
    // CLI parsing adapted from the example here
    // https://codeberg.org/ziglang/zig/pulls/30644

    const args = try init.minimal.args.toSlice(init.arena.allocator());

    if (args.len == 1) {
        std.debug.print("{s}", .{help});
        return;
    }

    var flags: struct {
        relay: ?[]const u8 = null,
        dest: ?[]const u8 = null,
        connect: ?[]const u8 = null,
    } = .{};

    {
        var i: usize = 1;
        while (i < args.len) : (i += 1) {
            if (to_option.get(args[i])) |opt| {
                switch (opt) {
                    .help => {
                        std.debug.print("{s}\n", .{help});
                        return;
                    },
                    .relay => {
                        i += 1;
                        if (i < args.len) {
                            flags.relay = args[i];
                        } else {
                            std.debug.print("-r/--relay requires a string\n", .{});
                            return error.InvalidArguments;
                        }
                    },
                    .dest => {
                        i += 1;
                        if (i < args.len) {
                            flags.dest = args[i];
                        } else {
                            std.debug.print("-d/--dest requires a string\n", .{});
                            return error.InvalidArguments;
                        }
                    },
                    .connect => {
                        i += 1;
                        if (i < args.len) {
                            flags.connect = args[i];
                        } else {
                            std.debug.print("-c/--connect requires a string\n", .{});
                            return error.InvalidArguments;
                        }
                    },
                }
            } else {
                std.debug.print("Unknown argument: {s}\n", .{args[i]});
                return error.InvalidArguments;
            }
        }
    }

    if (flags.connect != null and (flags.relay != null or flags.dest != null)) {
        std.debug.print("Incompatible arguments.\nCannot use --connect/-c with dest or relay.\n", .{});
        return error.InvalidArguments;
    }

    std.debug.print("relay: {s}\n", .{flags.relay orelse "<null>"});
    std.debug.print("dest: {s}\n", .{flags.dest orelse "<null>"});
    std.debug.print("connect: {s}\n", .{flags.connect orelse "<null>"});

    // const net_interface: std.Io.net.Interface = .{ .index = 1 };
    // std.debug.print("Interface: {s}\n", .{(try net_interface.name(init.io)).toSlice()});

    const linux_socket = blk: {
        const linux_socket = std.os.linux.socket(AF.PACKET, SOCK.RAW, 0);
        const errno = std.os.linux.errno(linux_socket);
        if (errno != .SUCCESS) {
            std.debug.print("Failed to open socket: {t}\n", .{errno});
            return error.Error; // TODO: better error
        }
        break :blk linux_socket;
    };
    const socket_fd = blk: {
        const socket_fd = std.os.linux.bind(@intCast(linux_socket), @bitCast(std.os.linux.sockaddr.ll{
            // https://codeberg.org/jeffective/gatorcat/src/commit/1da40c85c2d063368e2e5c130e654cb32b6bff0e/src/module/nic.zig#L137
            .protocol = std.mem.nativeToBig(u16, @as(u16, std.os.linux.ETH.P.ALL)),
            .ifindex = 1,
            .hatype = 0,
            .pkttype = 0,
            .halen = 0,
            .addr = @splat(0),
        }), @sizeOf(std.os.linux.sockaddr.ll));

        const errno = std.os.linux.errno(socket_fd);

        if (errno != .SUCCESS) {
            std.debug.print("Failed to create link layer socket: {t}\n", .{errno});
            return error.Error; // TODO: better error
        }
        break :blk socket_fd;
    };

    const EthIpUdp = struct {
        // eth
        dst_mac: [6]u8 = @splat(0xff),
        src_mac: [6]u8,
        eth_type: u16 = std.os.linux.ETH.P.IP,
        // ip
        ip_version: u4 = 4,
    };

    // const ip: std.Io.net.IpAddress = .{ .ip4 = .unspecified(0) };
    // const socket = try ip.bind(init.io, .{ .mode = .rdm, .protocol = .raw });
    // defer socket.close(init.io);

    // try socket.send(init.io, &.{ .ip4 = .{ .bytes = @splat(255), .port = 8888 } }, "foo");

    // var sock_buffer: [1500]u8 = undefined;
    // var raw_socket_writer: RawSocketWriter = try .init("enp7s0", &sock_buffer); // /proc/net/dev
    // var net_buffer: [1500]u8 = undefined;
    // var net_writer: NetWriter = try .init(&raw_socket_writer.interface, &net_buffer);
    // var client = try SaprusClient.init(&net_writer.interface);
    // defer client.deinit();

    // if (res.args.relay) |r| {
    //     const dest = parseDest(res.args.dest);
    //     try client.sendRelay(
    //         if (r.len > 0) r else "Hello darkness my old friend",
    //         dest,
    //     );
    //     return;
    // } else if (res.args.connect) |c| {
    //     if (false) {
    //         _ = client.connect(if (c.len > 0) c else "Hello darkness my old friend") catch |err| switch (err) {
    //             error.WouldBlock => null,
    //             else => return err,
    //         };
    //         return;
    //     }
    //     @panic("Not implemented");
    // }

    // return clap.helpToFile(.stderr(), clap.Help, &params, .{});
}

fn parseDest(in: ?[]const u8) [4]u8 {
    if (in) |dest| {
        if (dest.len <= 4) {
            var res: [4]u8 = @splat(0);
            @memcpy(res[0..dest.len], dest);
            return res;
        }

        const addr = std.Io.net.Ip4Address.parse(dest, 0) catch return "FAIL".*;
        return addr.bytes;
    }
    return "zap\x00".*;
}

const builtin = @import("builtin");
const std = @import("std");
const ArrayList = std.ArrayList;
const StaticStringMap = std.StaticStringMap;

const zaprus = @import("zaprus");
const SaprusClient = zaprus.Client;
const SaprusMessage = zaprus.Message;
const RawSocketWriter = zaprus.RawSocketWriter;

// Import C headers for network constants and structs
const c = @cImport({
    @cInclude("sys/socket.h");
    @cInclude("linux/if_packet.h");
    @cInclude("net/ethernet.h");
    @cInclude("sys/ioctl.h");
    @cInclude("net/if.h");
    @cInclude("arpa/inet.h");
});

const AF = std.os.linux.AF;
const SOCK = std.os.linux.SOCK;
// const NetWriter = zaprus.NetWriter;