/*
 * Tentun - covert tunneling project
 *
 * Copyright (C) 2003 David Gordon
 *
 *      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.
 */


#ifndef _TENTUN_LIB_H
#define _TENTUN_LIB_H

#include "config.h"

#include <sys/types.h>
#include <signal.h>
#include <errno.h>
#include <netinet/in.h>

#ifdef HAVE_LIBUTIL_H
#include <libutil.h>
#endif

#include "tentun.h"

#ifndef min
  #define min(a,b)    ( (a)<(b) ? (a):(b) )
#endif

int udp_session(struct tentun_host *host); 
void free_sopt(struct tentun_sopt *opt);
int connect_t(int s, struct sockaddr *svr, time_t timeout); 
int server_addr(struct sockaddr_in *addr, struct tentun_host *host);


/* IO cancelation */
extern volatile sig_atomic_t __io_canceled;

static inline void io_init(void)
{
	__io_canceled = 0;
}

static inline void io_cancel(void)
{
	__io_canceled = 1;
}

/* Read exactly len bytes (Signal safe)*/
static inline int read_n(int fd, char *buf, int len)
{
	register int t=0, w;

	while (!__io_canceled && len > 0) {
	  if( (w = read(fd, buf, len)) < 0 ){
	     if( errno == EINTR || errno == EAGAIN )
 	        continue;
	     return -1;
	  }
	  if( !w )
	     return 0;
	  len -= w; buf += w; t += w;
	}

	return t;
}   

/* Write exactly len bytes (Signal safe)*/
static inline int write_n(int fd, char *buf, int len)
{
	register int t=0, w;

	while (!__io_canceled && len > 0) {
 	  if( (w = write(fd, buf, len)) < 0 ){
	     if( errno == EINTR || errno == EAGAIN )
  	         continue;
	     return -1;
	  }
	  if( !w )
	     return 0;
	  len -= w; buf += w; t += w;
	}

	return t;
}


#endif /* _TENTUN_LIB_H */
