/* 
 * support.c
 *
 * used by dipcreg.c to do some common tasks
 *
 * By Kamran Karimi
 */

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <arpa/inet.h>

/* read nbytes from the network and put them in *ptr */
int readn(int fd, char *ptr, int nbytes)
{
 int nleft, nread;
 
 nleft = nbytes;
 while(nleft > 0)
 {
  nread = read(fd,ptr,nleft);
  if(nread < 0)
   return nread;   
  if(nread == 0) break;
  if(nread > 0)
  {
   nleft -= nread;
   ptr += nread;
  } 
 } 
 return (nbytes - nleft);
}  

/* send nbytes from *ptr to the network */
int writen(int fd, char *ptr, int nbytes)
{
 int nleft,nwritten;
 
 nleft = nbytes;
 while(nleft > 0)
 {
  nwritten = write(fd,ptr,nleft);
  if(nwritten < 0)
   return nwritten;
  if(nwritten == 0) break;
  if(nwritten > 0)
  {
   nleft -= nwritten;
   ptr += nwritten;
  } 
 } 
 return (nbytes - nleft);
}
 
/* get a socket connection to another waiting one */ 
int ring(int family, struct sockaddr *addr, int addr_len)
{
 int sockfd;
 
 if((sockfd = socket(family,SOCK_STREAM,0)) < 0) 
 {
  /*fprintf(stderr,"Support: socket() Failed BECAUSE %s\n",strerror(errno));*/
  return -1;
 }
 /* connect() may not be able to restart in case of an intr */
 if(connect(sockfd, addr, addr_len) < 0)
 {
  /*fprintf(stderr,"Support: connect() Failed BECAUSE %s\n",strerror(errno));*/
  close(sockfd);
  return -1;
 } 
 return sockfd;
}
