/*
 * Copyright 1988, 1989, 1990, 1991 Massachusetts Institute of Technology
 */
#include"structs.h"
#include <stdio.h>

acceptnew(sock)
     int sock;
{
  int i, len, mi;
  struct sockaddr client;
  struct sockaddr_in *client_in;
  char *temp, *inet_ntoa();

  for (i = 0; i < MAXSOCKETS; i++) {
    if (clients[i].sock == -1) {
      clients[i].sock = accept(sock,(struct sockaddr *)NULL,(int *)NULL);
      if (clients[i].sock == -1) {
	bsdsyslog(LOG_NOTICE,"Error accepting connection[%d]",i);
	return(0);
      }
      FD_SET(clients[i].sock,&allavail);
      if (DEBUG) printf("New client on connection %d, fd = %d\n", i,
			clients[i].sock);
      if (i+1 > max_connections) max_connections = i+1;
      num_connections++;
      clients[i].seglist = (RPD_SEGLIST *)NULL;
      clients[i].rev = -1;
      clients[i].db_rev = -1;
      clients[i].output = 0;
      clients[i].uid = 32767;
      len = sizeof(client);
      if (!getpeername(clients[i].sock, &client, &len)) {
	client_in = (struct sockaddr_in *)&client;
	if ( client_in->sin_family == AF_INET) {
#ifdef TCP_NODELAY	  
	  mi = 1;
	  setsockopt( clients[i].sock, IPPROTO_TCP, TCP_NODELAY, 
		     &mi, sizeof(int));
#endif /* TCP_NODELAY */
	  temp = inet_ntoa(client_in->sin_addr/*.s_addr*/);
	  clients[i].address = (char *)malloc(strlen(temp)+1 * sizeof(char));
	  if (clients[i].address)
	    strcpy(clients[i].address, temp);
	  else {
	    clients[i].local = 1;
	    bsdsyslog(LOG_NOTICE,"Unable to alloc INET address of client\n");
	  }
	  if (!strcmp(temp, localaddress)) 
	    clients[i].local = 1;
	  else clients[i].local = 0;
	}
	else {
	  clients[i].address = 
	    (char *)malloc(strlen(UNIX_STRING)+1 * sizeof(char));
	  if (clients[i].address)
	    strcpy(clients[i].address, UNIX_STRING);
	  else bsdsyslog(LOG_NOTICE,
			    "Unable to alloc UNIX address of client\n");
	  clients[i].local = 1;
	}
      }
      else {
	clients[i].local = 1;
	bsdsyslog(LOG_NOTICE,"Unable to get peername of new client\n");
      }
      return(0);
    }
  }
  return(0);
}
