/* 
   Copyright Andrew Tridgell 1997

   This is a anonymous cvs wrapper. It should be installed on port
   2401 in inetd.conf. It provides safe anonymous cvs access by
   automatically mirroring the contents of a cvs repository into
   a chrooted area and running cvs commands from within that area.

   You will need to install rsync, cvs and appropriate libraries
   and support files within the chrooted area. Exactly what files
   you will need is system dependent. It will be similar to
   those you will need for anonymous ftp

   */
   

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>

#include "pserver.h"

#define LOGFILE "pserver.log"

int main(int argc, char *argv[])
{
  pid_t pid;
  int status=0;
  FILE *f;

  /* the first thing we do is run rsync to ensure that the fake repository
     is uptodate */
  if ((pid = fork())) {
    waitpid(pid, &status, 0);
  } else {

    /* we close stdin etc to ensure that rsync does not fiddle with any
       user input */
    close(0);
    close(1);
    close(2);

    open("/dev/null", O_RDWR);
    open("/dev/null", O_RDWR);
    open("/dev/null", O_RDWR);

    if (setgid(GID))
      exit(1);
    
    if (setuid(UID))
      exit(1);

    if (chdir(CHROOT_PATH)) 
	    exit(1);

    return sync_trees();
  }


  /* now chroot - we don't want to do anything more outside the chrooted 
     area */
  if (chdir(CHROOT_PATH))
    exit(1);

  if (chroot(CHROOT_PATH))
    exit(1);


  /* log this connection */
  f = fopen(LOGFILE, "a");
  if (!f) exit(1);
  fprintf(f,"%s connect from %s (%s)\n", 
	  timestring(), 
	  client_name(0),
	  client_addr(0));
  fclose(f);

  /* lose root privilages */
  if (setgid(GID))
    exit(1);

  if (setuid(UID))
    exit(1);

  /* finally execute the cvs command - safely! */
  return execl("/bin/cvs", "cvs",
	       "-b/bin", "-l", "-z5", "--allow-root", FAKE_CVSROOT, "pserver", NULL);
}
