summaryrefslogtreecommitdiff
path: root/include/net.h
blob: 08c566a8a70ebc0f4755b80c1f11178c4a8caf42 (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
// SPDX-FileCopyrightText: 2024 Lizzy Fleckenstein <lizzy@vlhl.dev>
//
// SPDX-License-Identifier: AGPL-3.0-or-later

#ifndef NET_H
#define NET_H

#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdlib.h>
#include <poll.h>
#include <fcntl.h>
#include "str.h"
#include "ser.h"
#include "content.h"

#define SET_NONBLOCK(X) fcntl((X), F_SETFL, fcntl((X), F_GETFL, 0) | O_NONBLOCK)

#define PEER_INBUFFER_SIZE 0x100000 // 1MB
#define PEER_OUTBUFFER_SIZE 0x200000 // 2MB

typedef uint32_t pkt_header;

typedef struct {
	int socket;
	bool disco;
	str *name;
	struct {
		bool header;
		size_t len;
		size_t promised;
		uint8_t *buffer;
	} in;
	// TODO: ring buffer
	struct {
		size_t avail;
		size_t cursor;
		uint8_t *buffer;
	} out;
} peer;

#define SEND_PKT(CONN, TYPE, ...) \
	{ strbuf pkt = NILSBUF; \
	ser_pkt_type(&pkt, TYPE); \
	__VA_ARGS__ \
	if (!peer_send(&(CONN), pkt.data, pkt.len)) \
		fprintf(stderr, "failed to send " #TYPE " to %.*s\n", PSTR(*(CONN).name)); \
	free(pkt.data); }

void invalid_pkt(peer *p, str pkt);

int socket_create(const char *host, const char *port, bool server);
int socket_accept(int accept_fd);

void peer_init(peer *p, int socket, str *name);
void peer_free(peer *p);
struct pollfd peer_prepare(peer *p);
str peer_recv(peer *p, struct pollfd pfd);
bool peer_send(peer *p, void *data, size_t len);

#endif