/* listen.c

   Listen on the telnet port (or some user-specified port) for connections. */

/*
 * Copyright (c) 1995 RadioMail Corporation.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of RadioMail Corporation nor the names of its
 *    contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY RADIOMAIL CORPORATION AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
 * RADIOMAIL CORPORATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software was written for RadioMail Corporation by Ted Lemon
 * under a contract with Vixie Enterprises, and is based on an earlier
 * design by Paul Vixie.
 */

#ifndef lint
static char copyright[] =
"@(#) Copyright (c) 1995 RadioMail Corporation.  All rights reserved.\n";
#endif /* not lint */

#include "cdefs.h"
#include "osdep.h"
#include "global.h"
#include "mcap.h"

#include <sys/fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <syslog.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/errno.h>
#include <netdb.h>
#include <sys/stat.h>
#include <sys/resource.h>

void listener (port, addr, forkp)
     int port;
     struct in_addr *addr;
     int forkp;
{
  struct sockaddr_in name;
  struct servent *ent;
  int mpoolSock;
  int clientSock;
  int wstat;
  int timeout = 0;
  int flag;
  struct linger linger;
  int fd;
  int lastmodem = 0;

  name.sin_family = AF_INET;
  name.sin_port = port;
  name.sin_addr = *addr;
  memset (name.sin_zero, 0, sizeof (name.sin_zero));

  syslog (LOG_INFO, "Listening on %s, port %d\n",
	  inet_ntoa (name.sin_addr), htons (name.sin_port));
  if ((mpoolSock = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
    error ("Can't create mpool socket: %m");

  flag = 1;
  if (setsockopt (mpoolSock, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof flag) < 0)
    error ("Can't set SO_REUSEADDR option on mpool socket: %m");

  linger.l_onoff = 1;
  linger.l_linger = 10;
  if (setsockopt (mpoolSock,
		  SOL_SOCKET, SO_LINGER, &linger, sizeof linger) < 0)
    error ("Can't set SO_LINGER option on mpool socket: %m");

  if (bind (mpoolSock, (struct sockaddr *)&name, sizeof name) < 0)
    error ("Can't bind to mpool address: %m");

  if (listen (mpoolSock, 15) < 0)
    {
      syslog (LOG_ERR, "Can't listen on mpool socket: %m");
      exit (0);
    }

  /* Since we were able to get the port, we must be the anointed
     daemon (!), so blast whatever pid file may be dangling... */
  if ((fd = open (_PATH_MPOOL_PID, O_WRONLY | O_CREAT)) >= 0)
    {
      char obuf [20];
      sprintf (obuf, "%d\n", getpid ());
      write (fd, obuf, strlen (obuf));
      close (fd);
    }

  do {
    int pid;
    struct sockaddr_in name;
    int namelen = sizeof name;
    if ((clientSock =
	 accept (mpoolSock, (struct sockaddr *)&name, &namelen)) < 0)
      {
	syslog (LOG_ERR, "accept failed on mpool socket: %m");
	sleep (5);
	continue;
      }
    syslog (LOG_INFO, "connect from %s, port %d\n",
	    inet_ntoa (name.sin_addr), htons (name.sin_port));

    /* Try to assign modems in a ring by tracking the number of
       incoming connections.  This won't behave exactly the way we
       want, but it's better than setting up some sort of elaborate
       IPC between the parent and child (IMHO, anyway). */
    ++lastmodem;

    /* If we're supposed to fork children, make one now... */
    if (forkp)
      {
	if ((pid = fork ()) < 0)
	  syslog (LOG_ERR, "can't create child pid: %m");
	else if (pid)
	  {
	    close (clientSock);

	    /* Reap child processes that have exited... */
	    while (wait4 (-1, &wstat, WNOHANG, (struct rusage *)0) > 0)
	      ;
	    continue;
	  }
      }

    /* In child or debug thread... */
    close (mpoolSock);
    closelog ();
    /* Reopen stdin and stdout on client socket... */
    close (0);
    close (1);
    dup (clientSock);
    dup (clientSock);
    close (clientSock);
    exit (modemConnect (lastmodem));
  } while (1);
}
