112 lines
2.3 KiB
C
112 lines
2.3 KiB
C
#include <net.h>
|
|
#include <net_private.h>
|
|
#include <stddef.h>
|
|
#include <stdlib.h>
|
|
|
|
struct net_socket *net_connect(const union net_connect *const c)
|
|
{
|
|
struct net_socket *const s = calloc(1, sizeof *s);
|
|
|
|
if (!s)
|
|
goto failure;
|
|
|
|
static struct net_socket_domain *(*const f[])(const union net_connect *) =
|
|
{
|
|
[NET_DOMAIN_IPV4] = net_connect_ipv4,
|
|
[NET_DOMAIN_SERIAL] = net_connect_serial
|
|
};
|
|
|
|
if (!(s->s = f[c->common.domain](c)))
|
|
goto failure;
|
|
|
|
return s;
|
|
|
|
failure:
|
|
free(s);
|
|
return NULL;
|
|
}
|
|
|
|
int net_read(struct net_socket *const s, void *const buf, const size_t n)
|
|
{
|
|
static int (*const f[])(struct net_socket_domain *, void *, size_t) =
|
|
{
|
|
[NET_DOMAIN_IPV4] = net_read_ipv4,
|
|
[NET_DOMAIN_SERIAL] = net_read_serial
|
|
};
|
|
|
|
return f[s->d](s->s, buf, n);
|
|
}
|
|
|
|
int net_write(struct net_socket *const s, const void *const buf, const size_t n)
|
|
{
|
|
static int (*const f[])(struct net_socket_domain *, const void *, size_t) =
|
|
{
|
|
[NET_DOMAIN_IPV4] = net_write_ipv4,
|
|
[NET_DOMAIN_SERIAL] = net_write_serial
|
|
};
|
|
|
|
return f[s->d](s->s, buf, n);
|
|
}
|
|
|
|
int net_close(struct net_socket *const s)
|
|
{
|
|
if (!s)
|
|
return 0;
|
|
|
|
static int (*const f[])(struct net_socket_domain *) =
|
|
{
|
|
[NET_DOMAIN_IPV4] = net_close_ipv4,
|
|
[NET_DOMAIN_SERIAL] = net_close_serial
|
|
};
|
|
|
|
const int res = f[s->d](s->s);
|
|
|
|
free(s);
|
|
return res;
|
|
}
|
|
|
|
int net_update(struct net_socket *const s)
|
|
{
|
|
static int (*const f[])(struct net_socket_domain *) =
|
|
{
|
|
[NET_DOMAIN_IPV4] = net_update_ipv4,
|
|
[NET_DOMAIN_SERIAL] = net_update_serial
|
|
};
|
|
|
|
return f[s->d](s->s);
|
|
}
|
|
|
|
struct net_socket *net_server(const union net_server *const srv)
|
|
{
|
|
struct net_socket *const s = calloc(1, sizeof *s);
|
|
|
|
if (!s)
|
|
goto failure;
|
|
|
|
s->d = srv->common.domain;
|
|
|
|
static struct net_socket_domain *(*const f[])(const union net_server *) =
|
|
{
|
|
[NET_DOMAIN_IPV4] = net_server_ipv4,
|
|
[NET_DOMAIN_SERIAL] = net_server_serial
|
|
};
|
|
|
|
if (!(s->s = f[s->d](srv)))
|
|
goto failure;
|
|
|
|
failure:
|
|
net_close(s);
|
|
return NULL;
|
|
}
|
|
|
|
int net_init(void)
|
|
{
|
|
return net_init_ipv4() || net_init_serial();
|
|
}
|
|
|
|
void net_deinit(void)
|
|
{
|
|
net_deinit_ipv4();
|
|
net_deinit_serial();
|
|
}
|