1
0
mirror of https://github.com/janet-lang/janet synced 2024-11-16 13:44:48 +00:00
janet/src/core/net.c

795 lines
27 KiB
C
Raw Normal View History

/*
* Copyright (c) 2020 Calvin Rose
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#ifndef JANET_AMALG
#include "features.h"
#include <janet.h>
#include "util.h"
#endif
2020-05-28 15:39:40 +00:00
#ifdef JANET_NET
#ifdef JANET_WINDOWS
#include <winsock2.h>
#include <windows.h>
#include <ws2tcpip.h>
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "Advapi32.lib")
#else
2020-02-03 15:29:51 +00:00
#include <unistd.h>
#include <signal.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/tcp.h>
2020-02-03 15:29:51 +00:00
#include <netdb.h>
2020-05-07 19:54:03 +00:00
#include <fcntl.h>
#endif
2020-02-03 15:29:51 +00:00
/*
2020-05-28 15:39:40 +00:00
* Streams - simple abstract type that wraps a pollable + extra flags
2020-02-03 15:29:51 +00:00
*/
2020-05-28 15:39:40 +00:00
#define JANET_STREAM_READABLE 0x200
#define JANET_STREAM_WRITABLE 0x400
2020-05-31 20:46:01 +00:00
#define JANET_STREAM_ACCEPTABLE 0x800
2020-06-02 03:06:27 +00:00
#define JANET_STREAM_UDPSERVER 0x1000
static int janet_stream_close(void *p, size_t s);
2020-05-28 15:39:40 +00:00
static int janet_stream_mark(void *p, size_t s);
static int janet_stream_getter(void *p, Janet key, Janet *out);
static const JanetAbstractType StreamAT = {
"core/stream",
janet_stream_close,
2020-05-28 15:39:40 +00:00
janet_stream_mark,
janet_stream_getter,
JANET_ATEND_GET
};
2020-05-28 15:39:40 +00:00
typedef JanetPollable JanetStream;
2020-06-02 03:06:27 +00:00
static const JanetAbstractType AddressAT = {
"core/socket-address",
JANET_ATEND_NAME
};
#ifdef JANET_WINDOWS
#define JSOCKCLOSE(x) closesocket(x)
#define JSOCKDEFAULT INVALID_SOCKET
2020-04-30 18:26:14 +00:00
#define JLASTERR WSAGetLastError()
#define JSOCKVALID(x) ((x) != INVALID_SOCKET)
#define JEINTR WSAEINTR
#define JEWOULDBLOCK WSAEWOULDBLOCK
#define JEAGAIN WSAEWOULDBLOCK
#define JPOLL WSAPoll
#define JSock SOCKET
#define JReadInt long
#define JSOCKFLAGS 0
2020-05-28 15:39:40 +00:00
static JanetStream *make_stream(SOCKET fd, uint32_t flags) {
u_long iMode = 0;
JanetStream *stream = janet_abstract(&StreamAT, sizeof(JanetStream));
2020-05-28 15:39:40 +00:00
janet_pollable_init(stream, fd);
ioctlsocket(fd, FIONBIO, &iMode);
stream->flags = flags;
return stream;
}
#else
#define JSOCKCLOSE(x) close(x)
#define JSOCKDEFAULT 0
#define JLASTERR errno
#define JSOCKVALID(x) ((x) >= 0)
#define JEINTR EINTR
#define JEWOULDBLOCK EWOULDBLOCK
#define JEAGAIN EAGAIN
#define JPOLL poll
#define JSock int
#define JReadInt ssize_t
#ifdef SOCK_CLOEXEC
#define JSOCKFLAGS SOCK_CLOEXEC
#else
#define JSOCKFLAGS 0
#endif
2020-05-28 15:39:40 +00:00
static JanetStream *make_stream(int fd, uint32_t flags) {
JanetStream *stream = janet_abstract(&StreamAT, sizeof(JanetStream));
2020-05-28 15:39:40 +00:00
janet_pollable_init(stream, fd);
#ifndef SOCK_CLOEXEC
int extra = O_CLOEXEC;
#else
int extra = 0;
#endif
fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK | extra);
stream->flags = flags;
return stream;
}
#endif
/* We pass this flag to all send calls to prevent sigpipe */
#ifndef MSG_NOSIGNAL
#define MSG_NOSIGNAL 0
#endif
static int janet_stream_close(void *p, size_t s) {
(void) s;
JanetStream *stream = p;
2020-05-28 15:39:40 +00:00
if (!(stream->flags & JANET_POLL_FLAG_CLOSED)) {
JSOCKCLOSE(stream->handle);
janet_pollable_deinit(stream);
}
return 0;
}
2020-05-28 15:39:40 +00:00
static int janet_stream_mark(void *p, size_t s) {
(void) s;
janet_pollable_mark((JanetPollable *) p);
return 0;
}
/*
2020-05-28 15:39:40 +00:00
* State machine for read
*/
2020-02-03 15:29:51 +00:00
typedef struct {
2020-05-28 15:39:40 +00:00
JanetListenerState head;
int32_t bytes_left;
JanetBuffer *buf;
int is_chunk;
2020-06-02 03:06:27 +00:00
int is_recv_from;
2020-05-28 15:39:40 +00:00
} NetStateRead;
JanetAsyncStatus net_machine_read(JanetListenerState *s, JanetAsyncEvent event) {
2020-05-28 15:39:40 +00:00
NetStateRead *state = (NetStateRead *) s;
switch (event) {
default:
break;
case JANET_ASYNC_EVENT_MARK:
janet_mark(janet_wrap_buffer(state->buf));
break;
case JANET_ASYNC_EVENT_CLOSE:
/* Read is finished, even if chunk is incomplete */
janet_schedule(s->fiber, janet_wrap_nil());
return JANET_ASYNC_STATUS_DONE;
2020-05-28 15:39:40 +00:00
case JANET_ASYNC_EVENT_READ:
/* Read in bytes */
2020-05-28 21:51:11 +00:00
{
JanetBuffer *buffer = state->buf;
int32_t bytes_left = state->bytes_left;
janet_buffer_extra(buffer, bytes_left);
JReadInt nread;
2020-06-02 03:06:27 +00:00
struct sockaddr_in saddr;
socklen_t socklen = sizeof(saddr);
2020-05-28 21:51:11 +00:00
do {
2020-06-02 03:06:27 +00:00
if (state->is_recv_from) {
nread = recvfrom(s->pollable->handle, buffer->data + buffer->count, bytes_left, 0,
(struct sockaddr *)&saddr, &socklen);
} else {
nread = recv(s->pollable->handle, buffer->data + buffer->count, bytes_left, 0);
}
2020-05-28 21:51:11 +00:00
} while (nread == -1 && JLASTERR == JEINTR);
if (JLASTERR == JEAGAIN || JLASTERR == JEWOULDBLOCK) {
break;
}
2020-05-28 21:51:11 +00:00
/* Increment buffer counts */
if (nread > 0) {
buffer->count += nread;
bytes_left -= nread;
} else {
bytes_left = 0;
}
state->bytes_left = bytes_left;
2020-05-28 15:39:40 +00:00
2020-05-28 21:51:11 +00:00
/* Resume if done */
if (!state->is_chunk || bytes_left == 0) {
2020-06-02 03:06:27 +00:00
Janet resume_val;
if (state->is_recv_from) {
void *abst = janet_abstract(&AddressAT, socklen);
memcpy(abst, &saddr, socklen);
resume_val = janet_wrap_abstract(abst);
} else {
resume_val = nread > 0 ? janet_wrap_buffer(buffer) : janet_wrap_nil();
}
2020-05-28 21:51:11 +00:00
janet_schedule(s->fiber, resume_val);
return JANET_ASYNC_STATUS_DONE;
}
2020-05-28 21:51:11 +00:00
}
break;
2020-05-28 15:39:40 +00:00
}
return JANET_ASYNC_STATUS_NOT_DONE;
2020-05-28 15:39:40 +00:00
}
JANET_NO_RETURN static void janet_sched_read(JanetStream *stream, JanetBuffer *buf, int32_t nbytes) {
NetStateRead *state = (NetStateRead *) janet_listen(stream, net_machine_read,
2020-06-02 03:06:27 +00:00
JANET_ASYNC_LISTEN_READ, sizeof(NetStateRead));
2020-05-28 15:39:40 +00:00
state->is_chunk = 0;
state->buf = buf;
state->bytes_left = nbytes;
2020-06-02 03:06:27 +00:00
state->is_recv_from = 0;
2020-05-28 15:39:40 +00:00
janet_await();
}
JANET_NO_RETURN static void janet_sched_chunk(JanetStream *stream, JanetBuffer *buf, int32_t nbytes) {
NetStateRead *state = (NetStateRead *) janet_listen(stream, net_machine_read,
2020-06-02 03:06:27 +00:00
JANET_ASYNC_LISTEN_READ, sizeof(NetStateRead));
2020-05-28 15:39:40 +00:00
state->is_chunk = 1;
state->buf = buf;
state->bytes_left = nbytes;
2020-06-02 03:06:27 +00:00
state->is_recv_from = 0;
janet_await();
}
JANET_NO_RETURN static void janet_sched_recv_from(JanetStream *stream, JanetBuffer *buf, int32_t nbytes) {
NetStateRead *state = (NetStateRead *) janet_listen(stream, net_machine_read,
JANET_ASYNC_LISTEN_READ, sizeof(NetStateRead));
state->is_chunk = 0;
state->buf = buf;
state->bytes_left = nbytes;
state->is_recv_from = 1;
2020-05-28 15:39:40 +00:00
janet_await();
}
/*
2020-06-02 03:06:27 +00:00
* State machine for write/send-to
2020-05-28 15:39:40 +00:00
*/
typedef struct {
JanetListenerState head;
union {
JanetBuffer *buf;
const uint8_t *str;
} src;
int32_t start;
int is_buffer;
2020-06-02 03:06:27 +00:00
void *dest_abst;
2020-05-28 15:39:40 +00:00
} NetStateWrite;
JanetAsyncStatus net_machine_write(JanetListenerState *s, JanetAsyncEvent event) {
2020-05-28 15:39:40 +00:00
NetStateWrite *state = (NetStateWrite *) s;
switch (event) {
default:
break;
case JANET_ASYNC_EVENT_MARK:
janet_mark(state->is_buffer
2020-05-28 21:51:11 +00:00
? janet_wrap_buffer(state->src.buf)
: janet_wrap_string(state->src.str));
2020-06-02 03:06:27 +00:00
if (state->dest_abst != NULL) {
janet_mark(janet_wrap_abstract(state->dest_abst));
}
2020-05-28 15:39:40 +00:00
break;
case JANET_ASYNC_EVENT_CLOSE:
janet_schedule(s->fiber, janet_wrap_nil());
return JANET_ASYNC_STATUS_DONE;
2020-05-28 15:39:40 +00:00
case JANET_ASYNC_EVENT_WRITE: {
2020-05-28 21:51:11 +00:00
int32_t start, len;
const uint8_t *bytes;
start = state->start;
if (state->is_buffer) {
JanetBuffer *buffer = state->src.buf;
bytes = buffer->data;
len = buffer->count;
} else {
bytes = state->src.str;
len = janet_string_length(bytes);
}
if (start < len) {
int32_t nbytes = len - start;
JReadInt nwrote;
do {
2020-06-02 03:06:27 +00:00
void *dest_abst = state->dest_abst;
if (dest_abst) {
nwrote = sendto(s->pollable->handle, bytes + start, nbytes, 0,
(struct sockaddr *) dest_abst, janet_abstract_size(dest_abst));
} else {
nwrote = send(s->pollable->handle, bytes + start, nbytes, MSG_NOSIGNAL);
}
2020-05-28 21:51:11 +00:00
} while (nwrote == -1 && JLASTERR == JEINTR);
if (nwrote > 0) {
start += nwrote;
} else {
2020-05-28 21:51:11 +00:00
start = len;
}
2020-05-28 21:51:11 +00:00
}
state->start = start;
if (start >= len) {
janet_schedule(s->fiber, janet_wrap_nil());
return JANET_ASYNC_STATUS_DONE;
}
2020-05-28 15:39:40 +00:00
break;
2020-05-28 21:51:11 +00:00
}
break;
2020-02-03 15:29:51 +00:00
}
return JANET_ASYNC_STATUS_NOT_DONE;
2020-02-03 15:29:51 +00:00
}
2020-06-02 03:06:27 +00:00
JANET_NO_RETURN static void janet_sched_write_buffer(JanetStream *stream, JanetBuffer *buf, void *dest_abst) {
2020-05-28 15:39:40 +00:00
NetStateWrite *state = (NetStateWrite *) janet_listen(stream, net_machine_write,
2020-06-02 03:06:27 +00:00
JANET_ASYNC_LISTEN_WRITE, sizeof(NetStateWrite));
2020-05-28 15:39:40 +00:00
state->is_buffer = 1;
state->start = 0;
state->src.buf = buf;
2020-06-02 03:06:27 +00:00
state->dest_abst = dest_abst;
2020-05-28 15:39:40 +00:00
janet_await();
2020-02-03 15:29:51 +00:00
}
2020-05-28 15:39:40 +00:00
2020-06-02 03:06:27 +00:00
JANET_NO_RETURN static void janet_sched_write_stringlike(JanetStream *stream, const uint8_t *str, void *dest_abst) {
2020-05-28 15:39:40 +00:00
NetStateWrite *state = (NetStateWrite *) janet_listen(stream, net_machine_write,
2020-06-02 03:06:27 +00:00
JANET_ASYNC_LISTEN_WRITE, sizeof(NetStateWrite));
2020-05-28 15:39:40 +00:00
state->is_buffer = 0;
state->start = 0;
state->src.str = str;
2020-06-02 03:06:27 +00:00
state->dest_abst = dest_abst;
2020-05-28 15:39:40 +00:00
janet_await();
2020-02-03 15:29:51 +00:00
}
/*
2020-05-28 15:39:40 +00:00
* State machine for simple server
*/
2020-05-28 15:39:40 +00:00
typedef struct {
JanetListenerState head;
JanetFunction *function;
} NetStateSimpleServer;
JanetAsyncStatus net_machine_simple_server(JanetListenerState *s, JanetAsyncEvent event) {
2020-05-28 15:39:40 +00:00
NetStateSimpleServer *state = (NetStateSimpleServer *) s;
switch (event) {
default:
break;
case JANET_ASYNC_EVENT_INIT:
/* We know the pollable will be a stream */
janet_gcroot(janet_wrap_abstract(s->pollable));
break;
case JANET_ASYNC_EVENT_MARK:
janet_mark(janet_wrap_function(state->function));
break;
case JANET_ASYNC_EVENT_CLOSE:
janet_schedule(s->fiber, janet_wrap_nil());
janet_gcunroot(janet_wrap_abstract(s->pollable));
return JANET_ASYNC_STATUS_DONE;
2020-05-28 15:39:40 +00:00
case JANET_ASYNC_EVENT_READ: {
JSock connfd = accept(s->pollable->handle, NULL, NULL);
if (JSOCKVALID(connfd)) {
/* Made a new connection socket */
JanetStream *stream = make_stream(connfd, JANET_STREAM_READABLE | JANET_STREAM_WRITABLE);
Janet streamv = janet_wrap_abstract(stream);
JanetFiber *fiber = janet_fiber(state->function, 64, 1, &streamv);
janet_schedule(fiber, janet_wrap_nil());
}
break;
}
}
return JANET_ASYNC_STATUS_NOT_DONE;
}
2020-02-03 15:29:51 +00:00
2020-05-31 20:46:01 +00:00
/* State machine for accepting connections. */
typedef struct {
JanetListenerState head;
} NetStateAccept;
JanetAsyncStatus net_machine_accept(JanetListenerState *s, JanetAsyncEvent event) {
switch (event) {
default:
break;
case JANET_ASYNC_EVENT_CLOSE:
janet_schedule(s->fiber, janet_wrap_nil());
return JANET_ASYNC_STATUS_DONE;
case JANET_ASYNC_EVENT_READ: {
JSock connfd = accept(s->pollable->handle, NULL, NULL);
if (JSOCKVALID(connfd)) {
JanetStream *stream = make_stream(connfd, JANET_STREAM_READABLE | JANET_STREAM_WRITABLE);
Janet streamv = janet_wrap_abstract(stream);
janet_schedule(s->fiber, streamv);
return JANET_ASYNC_STATUS_DONE;
}
break;
}
}
return JANET_ASYNC_STATUS_NOT_DONE;
}
JANET_NO_RETURN static void janet_sched_accept(JanetStream *stream) {
2020-06-02 03:06:27 +00:00
janet_listen(stream, net_machine_accept, JANET_ASYNC_LISTEN_READ, sizeof(NetStateAccept));
2020-05-31 20:46:01 +00:00
janet_await();
}
2020-05-28 15:39:40 +00:00
/* Adress info */
2020-06-02 03:06:27 +00:00
static int janet_get_sockettype(Janet *argv, int32_t argc, int32_t n) {
JanetKeyword stype = janet_optkeyword(argv, argc, n, NULL);
int socktype = SOCK_DGRAM;
if ((NULL == stype) || !janet_cstrcmp(stype, "stream")) {
socktype = SOCK_STREAM;
} else if (janet_cstrcmp(stype, "datagram")) {
janet_panicf("expected socket type as :stream or :datagram, got %v", argv[n]);
}
return socktype;
}
/* Needs argc >= offset + 2 */
2020-06-02 03:06:27 +00:00
static struct addrinfo *janet_get_addrinfo(Janet *argv, int32_t offset, int socktype, int passive) {
/* Get host and port */
const char *host = janet_getcstring(argv, offset);
const char *port;
if (janet_checkint(argv[offset + 1])) {
port = (const char *)janet_to_string(argv[offset + 1]);
} else {
port = janet_getcstring(argv, offset + 1);
}
2020-02-03 15:29:51 +00:00
/* getaddrinfo */
struct addrinfo *ai = NULL;
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
2020-02-03 15:29:51 +00:00
hints.ai_family = AF_UNSPEC;
2020-06-02 03:06:27 +00:00
hints.ai_socktype = socktype;
hints.ai_flags = passive ? AI_PASSIVE : 0;
2020-02-03 15:29:51 +00:00
int status = getaddrinfo(host, port, &hints, &ai);
if (status) {
janet_panicf("could not get address info: %s", gai_strerror(status));
}
return ai;
}
/*
* C Funs
*/
2020-06-02 03:06:27 +00:00
static Janet cfun_net_sockaddr(int32_t argc, Janet *argv) {
janet_arity(argc, 2, 4);
int socktype = janet_get_sockettype(argv, argc, 2);
struct addrinfo *ai = janet_get_addrinfo(argv, 0, socktype, 0);
if (argc >= 3 && janet_truthy(argv[3])) {
/* Select all */
JanetArray *arr = janet_array(10);
struct addrinfo *iter = ai;
while (NULL != iter) {
void *abst = janet_abstract(&AddressAT, iter->ai_addrlen);
memcpy(abst, iter->ai_addr, iter->ai_addrlen);
janet_array_push(arr, janet_wrap_abstract(abst));
iter = iter->ai_next;
}
freeaddrinfo(ai);
return janet_wrap_array(arr);
} else {
/* Select first */
if (NULL == ai) {
janet_panic("no data for given address");
}
void *abst = janet_abstract(&AddressAT, ai->ai_addrlen);
memcpy(abst, ai->ai_addr, ai->ai_addrlen);
freeaddrinfo(ai);
return janet_wrap_abstract(abst);
}
}
static Janet cfun_net_connect(int32_t argc, Janet *argv) {
2020-06-02 03:06:27 +00:00
janet_arity(argc, 2, 3);
2020-06-02 03:06:27 +00:00
int socktype = janet_get_sockettype(argv, argc, 2);
struct addrinfo *ai = janet_get_addrinfo(argv, 0, socktype, 0);
/* Create socket */
2020-06-02 03:06:27 +00:00
JSock sock = JSOCKDEFAULT;
struct addrinfo *rp = NULL;
for (rp = ai; rp != NULL; rp = rp->ai_next) {
sock = socket(rp->ai_family, rp->ai_socktype | JSOCKFLAGS, rp->ai_protocol);
if (JSOCKVALID(sock)) break;
}
if (!JSOCKVALID(sock)) {
freeaddrinfo(ai);
janet_panic("could not create socket");
}
/* Connect to socket */
int status = connect(sock, ai->ai_addr, (int) ai->ai_addrlen);
freeaddrinfo(ai);
if (status == -1) {
JSOCKCLOSE(sock);
janet_panic("could not connect to socket");
}
/* Wrap socket in abstract type JanetStream */
JanetStream *stream = make_stream(sock, JANET_STREAM_READABLE | JANET_STREAM_WRITABLE);
return janet_wrap_abstract(stream);
}
static Janet cfun_net_server(int32_t argc, Janet *argv) {
2020-06-02 03:06:27 +00:00
janet_arity(argc, 2, 4);
/* Get host, port, and handler*/
2020-05-31 20:46:01 +00:00
JanetFunction *fun = janet_optfunction(argv, argc, 2, NULL);
2020-06-02 03:06:27 +00:00
int socktype = janet_get_sockettype(argv, argc, 3);
struct addrinfo *ai = janet_get_addrinfo(argv, 0, socktype, 1);
2020-02-03 15:29:51 +00:00
/* Check all addrinfos in a loop for the first that we can bind to. */
JSock sfd = JSOCKDEFAULT;
struct addrinfo *rp = NULL;
for (rp = ai; rp != NULL; rp = rp->ai_next) {
2020-05-07 12:55:08 +00:00
sfd = socket(rp->ai_family, rp->ai_socktype | JSOCKFLAGS, rp->ai_protocol);
if (!JSOCKVALID(sfd)) continue;
/* Set various socket options */
int enable = 1;
if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (char *) &enable, sizeof(int)) < 0) {
JSOCKCLOSE(sfd);
janet_panic("setsockopt(SO_REUSEADDR) failed");
}
#ifdef SO_NOSIGPIPE
if (setsockopt(sfd, SOL_SOCKET, SO_NOSIGPIPE, &enable, sizeof(int)) < 0) {
JSOCKCLOSE(sfd);
janet_panic("setsockopt(SO_NOSIGPIPE) failed");
}
#endif
#ifdef SO_REUSEPORT
if (setsockopt(sfd, SOL_SOCKET, SO_REUSEPORT, &enable, sizeof(int)) < 0) {
JSOCKCLOSE(sfd);
janet_panic("setsockopt(SO_REUSEPORT) failed");
}
#endif
/* Bind */
if (bind(sfd, rp->ai_addr, (int) rp->ai_addrlen) == 0) break;
JSOCKCLOSE(sfd);
2020-02-03 15:29:51 +00:00
}
2020-06-02 03:06:27 +00:00
freeaddrinfo(ai);
2020-02-03 15:29:51 +00:00
if (NULL == rp) {
janet_panic("could not bind to any sockets");
}
2020-06-02 03:06:27 +00:00
if (socktype == SOCK_DGRAM) {
/* Datagram server (UDP) */
if (NULL == fun) {
/* Server no handler */
JanetStream *stream = make_stream(sfd, JANET_STREAM_UDPSERVER | JANET_STREAM_READABLE);
return janet_wrap_abstract(stream);
} else {
/* Server with handler */
/* TODO - state machine */
janet_panic("nyi");
}
} else {
/* Stream server (TCP) */
/* listen */
int status = listen(sfd, 1024);
if (status) {
JSOCKCLOSE(sfd);
janet_panic("could not listen on file descriptor");
}
/* Put sfd on our loop */
if (NULL == fun) {
JanetStream *stream = make_stream(sfd, JANET_STREAM_ACCEPTABLE);
return janet_wrap_abstract(stream);
} else {
/* Server with handler */
JanetStream *stream = make_stream(sfd, 0);
NetStateSimpleServer *ss = (NetStateSimpleServer *) janet_listen(stream, net_machine_simple_server,
JANET_ASYNC_LISTEN_READ, sizeof(NetStateSimpleServer));
ss->function = fun;
return janet_wrap_abstract(stream);
}
2020-02-03 15:29:51 +00:00
}
2020-06-02 03:06:27 +00:00
}
2020-02-03 15:29:51 +00:00
2020-06-02 03:06:27 +00:00
static void check_stream_flag(JanetStream *stream, int flag) {
if (!(stream->flags & flag) || (stream->flags & JANET_POLL_FLAG_CLOSED)) {
const char *msg = "";
if (flag == JANET_STREAM_READABLE) msg = "readable";
if (flag == JANET_STREAM_WRITABLE) msg = "writable";
if (flag == JANET_STREAM_ACCEPTABLE) msg = "server";
if (flag == JANET_STREAM_UDPSERVER) msg = "datagram server";
janet_panicf("bad stream - expected %s stream", msg);
2020-05-31 20:46:01 +00:00
}
}
static Janet cfun_stream_accept(int32_t argc, Janet *argv) {
janet_fixarity(argc, 1);
JanetStream *stream = janet_getabstract(argv, 0, &StreamAT);
2020-06-02 03:06:27 +00:00
check_stream_flag(stream, JANET_STREAM_ACCEPTABLE);
2020-05-31 20:46:01 +00:00
janet_sched_accept(stream);
2020-02-03 15:29:51 +00:00
}
static Janet cfun_stream_read(int32_t argc, Janet *argv) {
janet_arity(argc, 2, 3);
JanetStream *stream = janet_getabstract(argv, 0, &StreamAT);
2020-06-02 03:06:27 +00:00
check_stream_flag(stream, JANET_STREAM_READABLE);
int32_t n = janet_getnat(argv, 1);
JanetBuffer *buffer = janet_optbuffer(argv, argc, 2, 10);
2020-05-28 15:39:40 +00:00
janet_sched_read(stream, buffer, n);
}
static Janet cfun_stream_chunk(int32_t argc, Janet *argv) {
janet_arity(argc, 2, 3);
JanetStream *stream = janet_getabstract(argv, 0, &StreamAT);
2020-06-02 03:06:27 +00:00
check_stream_flag(stream, JANET_STREAM_READABLE);
int32_t n = janet_getnat(argv, 1);
JanetBuffer *buffer = janet_optbuffer(argv, argc, 2, 10);
2020-05-28 15:39:40 +00:00
janet_sched_chunk(stream, buffer, n);
}
2020-06-02 03:06:27 +00:00
static Janet cfun_stream_recv_from(int32_t argc, Janet *argv) {
janet_fixarity(argc, 3);
JanetStream *stream = janet_getabstract(argv, 0, &StreamAT);
check_stream_flag(stream, JANET_STREAM_UDPSERVER);
int32_t n = janet_getnat(argv, 1);
JanetBuffer *buffer = janet_getbuffer(argv, 2);
janet_sched_recv_from(stream, buffer, n);
}
static Janet cfun_stream_close(int32_t argc, Janet *argv) {
janet_fixarity(argc, 1);
JanetStream *stream = janet_getabstract(argv, 0, &StreamAT);
janet_stream_close(stream, 0);
return janet_wrap_nil();
}
static Janet cfun_stream_write(int32_t argc, Janet *argv) {
janet_fixarity(argc, 2);
JanetStream *stream = janet_getabstract(argv, 0, &StreamAT);
2020-06-02 03:06:27 +00:00
check_stream_flag(stream, JANET_STREAM_WRITABLE);
if (janet_checktype(argv[1], JANET_BUFFER)) {
2020-06-02 03:06:27 +00:00
janet_sched_write_buffer(stream, janet_getbuffer(argv, 1), NULL);
} else {
JanetByteView bytes = janet_getbytes(argv, 1);
2020-06-02 03:06:27 +00:00
janet_sched_write_stringlike(stream, bytes.bytes, NULL);
}
}
static Janet cfun_stream_send_to(int32_t argc, Janet *argv) {
janet_fixarity(argc, 3);
JanetStream *stream = janet_getabstract(argv, 0, &StreamAT);
check_stream_flag(stream, JANET_STREAM_UDPSERVER);
void *dest = janet_getabstract(argv, 1, &AddressAT);
if (janet_checktype(argv[2], JANET_BUFFER)) {
janet_sched_write_buffer(stream, janet_getbuffer(argv, 2), dest);
} else {
JanetByteView bytes = janet_getbytes(argv, 2);
janet_sched_write_stringlike(stream, bytes.bytes, dest);
}
}
static Janet cfun_stream_flush(int32_t argc, Janet *argv) {
janet_fixarity(argc, 2);
JanetStream *stream = janet_getabstract(argv, 0, &StreamAT);
2020-06-02 03:06:27 +00:00
check_stream_flag(stream, JANET_STREAM_WRITABLE);
/* Toggle no delay flag */
int flag = 1;
setsockopt(stream->handle, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int));
flag = 0;
setsockopt(stream->handle, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int));
return argv[0];
}
static const JanetMethod stream_methods[] = {
{"chunk", cfun_stream_chunk},
{"close", cfun_stream_close},
{"read", cfun_stream_read},
{"write", cfun_stream_write},
{"flush", cfun_stream_flush},
2020-05-31 20:46:01 +00:00
{"accept", cfun_stream_accept},
2020-06-02 03:06:27 +00:00
{"send-to", cfun_stream_send_to},
{"recv-from", cfun_stream_recv_from},
{NULL, NULL}
};
static int janet_stream_getter(void *p, Janet key, Janet *out) {
(void) p;
if (!janet_checktype(key, JANET_KEYWORD)) return 0;
return janet_getmethod(janet_unwrap_keyword(key), stream_methods, out);
}
static const JanetReg net_cfuns[] = {
2020-06-02 03:06:27 +00:00
{
"net/address", cfun_net_sockaddr,
JDOC("(net/address host port &opt type)\n\n"
"Look up the connection information for a given hostname, port, and connection type. Returns "
"a handle that can be used to send datagrams over network without establishing a connection.")
},
{
"net/server", cfun_net_server,
2020-06-02 03:06:27 +00:00
JDOC("(net/server host port &opt handler type)\n\n"
2020-04-26 19:11:47 +00:00
"Start a TCP server. handler is a function that will be called with a stream "
"on each connection to the server. Returns a new stream that is neither readable nor "
2020-06-02 03:06:27 +00:00
"writeable. If handler is nil or not provided, net/accept must be used to get the next connection "
"to the server. The type parameter specifies the type of network connection, either "
"a stream (usually tcp), or datagram (usually udp). If not specified, the default is "
"stream.")
2020-05-31 20:46:01 +00:00
},
{
"net/accept", cfun_stream_accept,
JDOC("(net/accept stream)\n\n"
"Get the next connection on a server stream. This would usually be called in a loop in a dedicated fiber. "
"Returns a new duplex stream which represents a connection to the client.")
2020-04-26 19:11:47 +00:00
},
{
"net/read", cfun_stream_read,
JDOC("(net/read stream nbytes &opt buf)\n\n"
"Read up to n bytes from a stream, suspending the current fiber until the bytes are available. "
"If less than n bytes are available (and more than 0), will push those bytes and return early. "
"Returns a buffer with up to n more bytes in it.")
2020-04-26 19:11:47 +00:00
},
{
"net/chunk", cfun_stream_chunk,
JDOC("(net/chunk stream nbytes &opt buf)\n\n"
"Same a net/read, but will wait for all n bytes to arrive rather than return early.")
2020-04-26 19:11:47 +00:00
},
{
"net/write", cfun_stream_write,
JDOC("(net/write stream data)\n\n"
"Write data to a stream, suspending the current fiber until the write "
"completes. Returns stream.")
},
2020-06-02 03:06:27 +00:00
{
"net/send-to", cfun_stream_send_to,
JDOC("(net/send-to stream dest data)\n\n"
"Writes a datagram to a server stream. dest is a the destination address of the packet. "
"Returns stream.")
},
{
"net/recv-from", cfun_stream_recv_from,
JDOC("(net/recv-from stream nbytes buf)\n\n"
"Receives data from a server stream and puts it into a buffer. Returns the socket-address the "
"packet came from.")
},
{
"net/flush", cfun_stream_flush,
JDOC("(net/flush stream)\n\n"
"Make sure that a stream is not buffering any data. This temporarily disables Nagle's algorithm. "
"Use this to make sure data is sent without delay. Returns stream.")
},
2020-04-26 19:11:47 +00:00
{
"net/close", cfun_stream_close,
JDOC("(net/close stream)\n\n"
"Close a stream so that no further communication can occur.")
},
{
"net/connect", cfun_net_connect,
2020-06-02 03:06:27 +00:00
JDOC("(net/connect host porti &opt type)\n\n"
2020-04-26 19:11:47 +00:00
"Open a connection to communicate with a server. Returns a duplex stream "
2020-06-02 03:06:27 +00:00
"that can be used to communicate with the server. Type is an optional keyword "
"to specify a connection type, either :stream or :datagram. The default is :stream. ")
},
{NULL, NULL, NULL}
};
void janet_lib_net(JanetTable *env) {
2020-05-28 15:39:40 +00:00
janet_core_cfuns(env, NULL, net_cfuns);
}
void janet_net_init(void) {
#ifdef JANET_WINDOWS
WSADATA wsaData;
janet_assert(!WSAStartup(MAKEWORD(2, 2), &wsaData), "could not start winsock");
#endif
}
void janet_net_deinit(void) {
#ifdef JANET_WINDOWS
WSACleanup();
#endif
}
2020-05-28 15:39:40 +00:00
#endif