/*
 *******************************************************************
 * $Author: lindner $
 * $Revision: 1.4 $
 * $Date: 91/04/10 12:37:09 $
 * $Source: /export/mermaid/staff/lindner/gopherd/RCS/gopherd.c,v $
 *******************************************************************
 */


/* Derived from an 
 * Example of server using TCP protocol
 * pp 284-5 Stevens UNIX Network Programming
 */

#include "gopherd.h"

char Zehostname[128];
int GopherPort = GOPHER_PORT;

void
main(argc, argv)
  int 	argc;
  char 	*argv[];
{
     int sockfd;
     int newsockfd;
     int clilen;
     int childpid;
     int i;

     struct sockaddr_in cli_addr;
     struct sockaddr_in serv_addr;


     pname = argv[0];

     /*** We probably shouldn't do this, since only one process can digitize 
       simultaneously, but of course we hate defunct processes!  ***/

     daemon_start(0);

     /** Open a TCP socket (an internet stream socket **/
     
     if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
	  err_dump("server: can't open stream socket");
     
     /*
      * Bind our local address so that the client can send to us
      */
     
     bzero((char *) &serv_addr, sizeof(serv_addr));
     serv_addr.sin_family 		= AF_INET;
     serv_addr.sin_addr.s_addr 	= htonl(INADDR_ANY);
     serv_addr.sin_port		= htons(GopherPort);
     
     if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) <0)
	  err_dump("server: can't bind local address");
     
     listen(sockfd, 5);
     
     for ( ; ; ) {
	  /*
	   * Wait for a connection from a client process.
	   * This is an example of a concurrent server.
	   */
	  
	  clilen = sizeof(cli_addr);
	  newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr,
			     &clilen);
	  
	  if (newsockfd < 0)
	       err_dump("server: accept error");
	  
	  if ( (childpid = fork()) < 0)
	       err_dump("server: fork error");
	  
	  else if (childpid == 0) {	/* Child process */
	       close(sockfd);		/* close original socket */

	       if (gethostname(Zehostname, 128) !=0 )
		    strcpy(Zehostname, "<<no-name>>");


	       while(do_command(newsockfd)!=0);	/* process the request */
	       exit(0);
	  }
	  /** clean up any zombie children **/
	  sig_child();

	  close(newsockfd); 		/* parent process */
     }
}


#define BUFSIZE 1464

int
do_command(sockfd)
int sockfd;
{
     FILE *Play;
     unsigned char in[BUFSIZE];
     register int i, j;

     char inputline[MAXLINE];
     int length;		/* Length of the command line */

     /*** Send out the Banner Line ***/
/*     writestring(sockfd, "gopher 1.0 sound server\r\n");*/
     
     /** Just ignore what ever the client sends to us and whack out sound **/
     i = readline(sockfd, inputline, MAXLINE);

/*     writestring(sockfd, "+ Okee dokee, here comes the sound\r\n");*/

     Play = popen("record -v 10 -", "r");
     while(1) {

	  for (i= 0; i<BUFSIZE; i++)
	       in[i] = getc(Play);

	  j = writen(sockfd, in, BUFSIZE);

     }
}



