#include "defs.h"
#include "rpc.h"
#include "funcs.h"

int
net_socket(type, addr)
int type;
struct net_addr *addr;
{
    short buf[2 + sizeof (struct net_addr) / sizeof (short)];

    buf[0] = FUNC_SOCKET;
    buf[1] = (short)type;
    if (addr)
	*(struct net_addr *)&buf[2] = *addr;
    (void)rpc_call(net_handle, sizeof buf, sizeof buf, buf);
    if (buf[0] < 0) {
	neterrno = buf[2];
	if (neterrno == NETERR_ERRNO)
	    map_errno(buf[1]);
	return -1;
    }
    if (addr)
	*addr = *(struct net_addr *)&buf[2];
    return buf[0];
}

int
net_info(fd, ni)
int fd;
struct net_info *ni;
{
    short buf[1 + sizeof (struct net_info) / sizeof (short)];

    buf[0] = FUNC_INFO;
    buf[1] = (short)fd;
    (void)rpc_call(net_handle, sizeof buf, 4, buf);
    if (buf[0] < 0) {
	neterrno = buf[2];
	if (neterrno == NETERR_ERRNO)
	    map_errno(buf[1]);
	return -1;
    }
    *ni = *(struct net_info *)&buf[1];
    return buf[0];
}

int
net_accept(fd, addr)
int fd;
struct net_addr *addr;
{
    short buf[1 + sizeof (struct net_addr) / sizeof (short)];

    buf[0] = FUNC_ACCEPT;
    buf[1] = (short)fd;
    (void)rpc_call(net_handle, sizeof buf, 4, buf);
    if (buf[0] < 0) {
	neterrno = buf[2];
	if (neterrno == NETERR_ERRNO)
	    map_errno(buf[1]);
	return -1;
    }
    if (addr)
	*addr = *(struct net_addr *)&buf[1];
    return buf[0];
}

int
net_select(nfds, ifds, ofds)
int nfds;
unsigned long *ifds, *ofds;
{
    short buf[6];

    buf[0] = FUNC_SELECT;
    buf[1] = (short)nfds;
    *(unsigned long *)&buf[2] = ifds ? *ifds : 0;
    *(unsigned long *)&buf[4] = ofds ? *ofds : 0;
    (void)rpc_call(net_handle, sizeof buf, sizeof buf, buf);
    if (buf[0] < 0) {
	neterrno = buf[2];
	if (neterrno == NETERR_ERRNO)
	    map_errno(buf[1]);
	return -1;
    }
    if (ifds)
	*ifds = *(unsigned long *)&buf[2];
    if (ofds)
	*ofds = *(unsigned long *)&buf[4];
    return buf[0];
}
