summaryrefslogtreecommitdiff
path: root/src/cmd/netstack/netstack.c
blob: 3876df9dc300840e30dfcbe5f086d96ac2769954 (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
77
78
79
#include "proto.h"
#include "util.h"
#include <camellia.h>
#include <camellia/compat.h>
#include <camellia/syscalls.h>
#include <err.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <thread.h>

struct net_state state = {0};

void network_thread(void *arg) { (void)arg;
	const size_t buflen = 4096;
	char *buf = malloc(buflen);
	for (;;) {
		long ret = _sys_read(state.raw_h, buf, buflen, -1);
		if (ret < 0) break;
		ether_parse((void*)buf, ret);
	}
	free(buf);
}

void fs_thread(void *arg);

int main(int argc, char **argv) {
	char *path;
	if (argc < 4) {
		fprintf(stderr, "usage: netstack iface ip gateway\n");
		return 1;
	}

	if (asprintf(&path, "%s/net", argv[1]) < 0) {
		errx(1, "asprintf failed for some reason");
	}
	state.raw_h = camellia_open(path, OPEN_RW);
	if (state.raw_h < 0) {
		err(1, "open %s", path);
		return 1;
	}
	free(path);

	if (asprintf(&path, "%s/mac", argv[1]) < 0) {
		errx(1, "asprintf failed for some reason");
	}
	hid_t h = camellia_open(path, OPEN_READ);
	if (h < 0) {
		err(1, "open %s", path);
		return 1;
	}
	if (_sys_read(h, state.mac, 6, 0) != 6) {
		errx(1, "can't read mac", path);
		return 1;
	}
	_sys_close(h);
	free(path);

	if (ip_parse(argv[2], &state.ip) < 0) {
		errx(1, "invalid ip: %s", argv[2]);
		return 1;
	}
	if (ip_parse(argv[3], &state.gateway) < 0) {
		errx(1, "invalid gateway: %s", argv[3]);
		return 1;
	}

	setproctitle(
		"ip=%s gw=%s mac=%02x:%02x:%02x:%02x:%02x:%02x", argv[2], argv[3],
		state.mac[0], state.mac[1], state.mac[2], state.mac[3], state.mac[4],
		state.mac[5]
	);
	arp_request(state.gateway);
	thread_create(0, network_thread, NULL);
	thread_create(0, fs_thread, NULL);
	_sys_await();
	return 0;
}