/*
 * Copyright (c) 2003-2012
 * Distributed Systems Software.  All rights reserved.
 * See the file LICENSE for redistribution information.
 *
 * $Id: net.h 2594 2012-10-19 17:28:49Z brachman $
 */

#ifndef _NET_H_
#define _NET_H_

#include <sys/types.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>

typedef enum Net_connection_type {
  NET_TCP        = 0,
  NET_SSL        = 1,
  NET_SSL_VERIFY = 2,
  NET_HTTP       = 3
} Net_connection_type;

#ifndef HAVE_GETNAMEINFO
#define NI_DGRAM       0x01
#define NI_NAMEREQD    0x02
#define NI_NOFQDN      0x04
#define NI_NUMERICHOST 0x08
#define NI_NUMERICSERV 0x10

#define EAI_FAMILY      5
#define EAI_NONAME      8
#define EAI_SYSTEM     11

#ifdef __cplusplus
extern "C" {
#endif

extern int getnameinfo(const struct sockaddr *sa, socklen_t salen,
					   char *host, size_t hostlen, char *serv, size_t servlen,
					   int flags);
#ifdef __cplusplus
}
#endif

#endif

#ifdef __cplusplus
extern "C" {
#endif

extern int net_tcp_nodelay(int sd);
extern int net_socket_reuseaddr(int sd);
extern int net_set_nonblocking(int sd, char **errmsg);
extern int net_set_blocking(int sd, char **errmsg);
extern in_port_t net_get_service_port(char *portname, char *default_portname,
									  char **errmsg);
extern int net_write(int sd, void *buf, size_t buflen);
extern int net_write_str(int sd, char *mesg);
extern int net_connect_to_server_ssl(char *hostname, in_port_t port,
									 Net_connection_type ct,
									 char *ssl_prog, char *ssl_prog_args,
									 char *ssl_prog_client_crt,
									 char *ssl_prog_ca_crt,
									 int *read_fd, int *write_fd);
extern int net_connect_to_server(char *hostname, in_port_t port,
								 int *read_fd, int *write_fd);
extern int net_input_or_timeout(int sd, struct timeval *timeout);
extern struct sockaddr_in *net_make_sockaddr(char *hostname, in_port_t port);
extern char *net_sockaddr_name(struct sockaddr *sa, socklen_t salen);
extern char *net_socket_lname(int sd);
extern char *net_socket_rname(int sd);
extern struct sockaddr *net_socket_laddr(int sd);
extern struct sockaddr *net_socket_raddr(int sd);

extern int net_accept_or_timeout(int sd, struct sockaddr *from,
								 struct timeval *timeout);
extern int net_make_server_socket(char *hostname, in_port_t port,
								  int *sdp, struct sockaddr_in **namep);
extern int net_parse_hostname_port(char *str, char **hostname, char **port,
								   in_port_t *portnum);

#ifdef __cplusplus
}
#endif

#endif
