/* accept.c (rsxnt) -- Copyright (c) 1996-1997 Rainer Schnitker */

#include <rsxnt.h>
#include <rsxntso.h>

int __accept (int fd, struct sockaddr *addr, int *paddrlen)
{
    EMXPROCESS *p = _rsxnt_get_process_ptr();
    int s, newfd;

    if (!_rsxnt_socket_inited)
      return _rsxnt_errno(ENETDOWN);

    if (fd >= N_FILES || fd < 0)
        return _rsxnt_errno(EBADF);
    if (p->file[fd].f_handle == INVALID_HANDLE_VALUE)
        return _rsxnt_errno(EBADF);
    if (p->file[fd].f_mode != HT_SOCKET)
        return _rsxnt_errno(EBADF);

    s = (*wsa_accept) ((int)p->file[fd].f_handle, addr, paddrlen);
    if (s == SOCKET_ERROR)
        return _rsxnt_socket_errno();

    newfd = _rsxnt_get_new_file(_rsxnt_get_process_ptr());

    if (newfd < 0) {
        (*wsa_closesocket)(s);
        return _rsxnt_errno(EMFILE);
    }
    else {
        EMXPROCESS *p = _rsxnt_get_process_ptr();

        p->file[newfd].f_handle = (HANDLE) s;
        p->file[newfd].f_mode = HT_SOCKET;
        p->file[newfd].f_flags = 0;

        return newfd;
    }
}
