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
|
#pragma once
#include <al/types.h>
#include <al/str.h>
#ifdef NAUNET_ON_WINDOWS
#include "../winwrap.h"
#else
#include <unistd.h>
#include <sys/un.h>
#include <poll.h>
#include <sys/eventfd.h>
#endif
enum {
NNWT_SOCKET_TCP = 0,
NNWT_SOCKET_UDP,
NNWT_SOCKET_UNIX
};
enum {
NNWT_SOCKET_NONBLOCKING = 1,
NNWT_SOCKET_NODELAY = 1 << 1,
NNWT_SOCKET_REUSE_ADDR = 1 << 2
};
// @TODO: Guard against EINTR?
// https://github.com/kovidgoyal/kitty/blob/master/kitty/safe-wrappers.h
struct nn_socket {
u8 type;
#ifdef NAUNET_ON_WINDOWS
SOCKET fd;
s32 internal_fd;
SOCKADDR_IN addr_in;
#else
s32 fd;
struct addrinfo *addrinfo;
struct sockaddr_un addr_un;
u32 acceptconn;
#endif
};
#ifdef NAUNET_ON_WINDOWS
#define nn_read _read
#define nn_write _write
#else
#define nn_read read
#define nn_write write
#endif
#ifndef NAUNET_ON_WINDOWS // Posix-only helpers.
#define nn_pollfd pollfd
#define nn_nfds nfds_t
#define nn_eventfd eventfd
void nn_fd_set_blocking(s32 fd, bool blocking);
s32 nn_poll_fds(struct nn_pollfd *fds, nn_nfds nfds, s64 timeout_ns);
#endif
bool nn_socket_init(struct nn_socket *sock, s32 flags);
void nn_socket_set_blocking(struct nn_socket *sock, bool blocking);
void nn_socket_set_nodelay(struct nn_socket *sock, s32 nodelay);
void nn_socket_set_reuse_addr(struct nn_socket *sock, s32 reuse_addr);
u32 nn_socket_get_send_buf(struct nn_socket *sock);
void nn_socket_set_send_buf(struct nn_socket *sock, u32 sndbuf);
u32 nn_socket_get_recv_buf(struct nn_socket *sock);
void nn_socket_set_recv_buf(struct nn_socket *sock, u32 rcvbuf);
bool nn_socket_set(struct nn_socket *sock, str *addr, u16 port);
bool nn_socket_bind(struct nn_socket *sock, str *addr, u16 port);
bool nn_socket_listen(struct nn_socket *sock);
bool nn_socket_accept(struct nn_socket *sock, struct nn_socket *c, s32 flags);
bool nn_socket_connect(struct nn_socket *sock, str *addr, u16 port);
s32 nn_socket_get_fd(struct nn_socket *sock);
ssize_t nn_socket_read(struct nn_socket *sock, void *buf, size_t size);
ssize_t nn_socket_write(struct nn_socket *sock, void *buf, size_t size);
ssize_t nn_socket_sendto(struct nn_socket *sock, void *buf, size_t size);
ssize_t nn_socket_recvfrom(struct nn_socket *sock, void *buf, size_t size);
bool nn_socket_check_error(ssize_t ret);
void nn_socket_shutdown(struct nn_socket *sock);
void nn_socket_close(struct nn_socket *sock);
void nn_socket_cleanup(struct nn_socket *sock);
|