#ifndef __DWC_FD_H
#define __DWC_FD_H

/*--------------------------------------------------------------------------
 *  Copyright (c) 2001-2004 Igor Daniloff. 
 *	All rights reserved.
 *
 * By using this file, you agree to the terms and conditions set
 * forth in the LICENSE file which can be found at this directory.
 *------------------------------------------------------------------------*/
 
/* $Id: dwc_fd.h,v 1.19.6.1 2009/09/30 10:06:51 akorkov Exp $ */

#include <sys/types.h>
#if defined(__UNIX_DW) && !defined(FreeBSD_DW)
#include <sys/select.h>
#endif /* UNIX and not FreeBSD */
#include <stdarg.h>
#include "dwc_type.h"
#include "dwc_timo.h"

#ifdef  __cplusplus
extern "C" {
#endif

#if defined(__WIN32_DW) 

#include <winsock.h>

#define WAS_INTERRUPTED                 (WSAGetLastError() == WSAENTR)
#define IN_PROGRESS                     (WSAGetLastError() == WSAEWOULDBLOCK)
#define SOCK_ERR( retval )              ((retval) == SOCKET_ERROR)
#define DWC_FD_CHECK( fd, who, expr )   NOP
typedef SOCKET                          DWC_fdsocket_t;

#else /* not __WIN32_DW */

#include <sys/socket.h>
#include <errno.h>
#include <string.h>

typedef dwc_fd_t                        DWC_fdsocket_t;

#define INVALID_SOCKET                  -1
#define WAS_INTERRUPTED                 (errno == EINTR)
#define IN_PROGRESS                     (errno == EINPROGRESS)
#define SOCK_ERR( retval )              ((retval) < 0)
#define DWC_FD_CHECK( fd, who, expr )\
BEGIN_MACRO\
    if( (fd) >= FD_SETSIZE )\
    {\
        printLib( DW_LL_ERROR, "%s: descriptor %d is larger that FD_SETSIZE = %d - %s", (who), (fd), FD_SETSIZE, strerror(errno) ); \
        expr;\
    }\
END_MACRO

#endif /* __WIN32_DW */

typedef DWC_fdsocket_t      dwc_fdsocket_t;

extern DWC_error_code_t     bind_socket ( DWC_fdsocket_t sock, struct sockaddr* addr, DWC_socklen_t len );
extern DWC_error_code_t     listen_socket ( DWC_fdsocket_t sock, int backlog );
extern DWC_error_code_t     accept_socket ( DWC_fdsocket_t sock, struct sockaddr* addr, DWC_socklen_t* plen, DWC_fdsocket_t *newsock );
extern DWC_error_code_t     connect_socket ( DWC_fdsocket_t sock, struct sockaddr* addr, DWC_socklen_t len, DWC_timeout_t timeout );
extern DWC_error_code_t     send_socket ( DWC_fdsocket_t sock, DWC_pointer_t buf, DWC_length_t *len, DWC_timeout_t timo );
extern DWC_error_code_t     recv_socket ( DWC_fdsocket_t sock, DWC_pointer_t buf, DWC_length_t *len, DWC_timeout_t timo );
extern DWC_string_t         socket_error ( void );
extern DWC_bool_t           set_nonblocking_fd( DWC_fdsocket_t fd );

#ifdef  __cplusplus
}
#endif

#endif /* __DWC_FD_H */
