/*
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Library General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#ifndef _SOCKET_
#define _SOCKET_

#include <stdarg.h>
#include "networklib.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>

#ifdef USE_SOCKET_SSL
#include <openssl/bio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#endif

typedef enum {
  SOCK_CONNECTED,
  SOCK_DISCONNECTED
} SocketState;

struct Socket {
  int fd;
  SocketState state;
  char *host;
  char *port;
  char *proto;
  unsigned int use_ssl;
  unsigned int ssl_verify;
#ifdef USE_SOCKET_SSL
  BIO *bio;
  SSL_CTX *ctx;
#endif
};
typedef struct Socket Socket;
  
struct ServerSocket {
  int fd;
  char *addr;
  char *port;
  char *proto;
};
typedef struct ServerSocket ServerSocket;

typedef enum {
  STD_ERROR,
  OPENSSL_ERROR
} ErrType;

typedef enum {
  SOCK_ERR = 0,
  SOCK_OK = 1,
  SOCK_SSL_VERIFY_ERR = 2,
  SOCK_SSL_CN_MISMATCH_ERR = 3,
  SOCK_SSL_NO_PEER_CERT_ERR = 4
} SocketConnectStatus;

const char * socket_strerror(int);
void set_socket_ssl(unsigned int);
unsigned int get_socket_ssl(void);
void set_ssl_pathstore(char *);
char * get_ssl_pathstore(void);
#ifdef USE_SOCKET_SSL
int BIO_read_buffer(BIO *, void *, int);
int BIO_readline(BIO *, char *, int);
char * X509_get_verify_error_string(unsigned int);
#endif

ServerSocket *server_socket_new(const char *, const char *, const char *);
Socket *server_socket_accept(ServerSocket *);
int server_socket_connect(ServerSocket *);
int server_socket_disconnect(ServerSocket *);
int server_socket_destroy(ServerSocket *);
Socket *socket_new(const char *, const char *, const char *);
int socket_bind(Socket *, const char *, const char *);
int socket_connect(Socket *);
int socket_disconnect(Socket *);
int socket_destroy(Socket *);
int socket_readline(Socket *, char * , int );
int socket_read(Socket *, char * , int );
int socket_write(Socket *, int, const char *, ...);
int socket_rawrite(Socket *, int, const char *, int);

#endif