/*
 * podfuk-smb
 *
 * A modified podfuk to provide a Network Neighbourhood type arrangement
 * within a Unix filesystem.
 *
 * Podfuk pretends to be the Coda cache manager Venus.  It intercepts
 * filesystem calls and passes them through smbw calls.  Information about
 * the Venus protocol can be found at:
 *
 * http://www.coda.cs.cmu.edu/doc/html/kernel-venus-protocol.html
 *
 * Based on podfuk.c by Pavel Machek.
 *
 * Copyright 2000 Tim Potter, tpot@linuxcare.com.au
 * Copyright 1999 Pavel Machek, pavel@ucw.cz
 *
 */

/* TTD:
 add timeouts for non-operative ftp sites
 a lookup request precipitates a login & read;
               is this neccessary for the root?
 how are we going to clean up the vfid chain?
 	there could be an "infinite" number of entries
 */

   /* Coda/Venus in a nutshell:
    * Coda is a filesystem, lives in the kernel
    * Venus is an app; podfuk is a replacement for venus
    * When a coda mount needs service, it sends a message
    *   up to podfuk through a pipe
    * Coda/Podfuk both open /dev/cfs0 and make ioctl calls
    * Message includes ViceFid (coda file/dir handle)
    *   which is: u32 volume-id, u32 node-id, u32 unique-num
    * Each file has an attribute struct: very similar to inode
    *
    * Typ sequence of calls to podfuk from coda:
    * file read: access(), open(), close()
    *    (the read() is done through the local file)
    * dir listing: access(), open(), lookup(), access(), close()
    * file write: lookup(file), access(parent), create(file), getattr(),
    *    open(), close(), setattr()
    */

/* When we get error return, we _must_ return error. We should log error, because someone forgot to set return code */

#define ERRNO (errno?errno:ENOCSI)

#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/time.h>
#include <sys/fsuid.h>
#include <signal.h>
#include <unistd.h>

#include <linux/coda.h>

#include "podfuk-smb-auth.h"

#define PARANOIA 1

#define VERSION_STRING "3.1"

#define MOUNT_POINT_STRING "/smb"

/* There is nothing magic about these constants. I just selected them
 * so that kernel does not complain too loudly.  */
#define MY_VOL   0x01234567
#define MY_VNODE 0xffffffff
#define MY_INODE 0x12345678
#define MK_FID(f,v,n,u) {f.Volume=v;f.Vnode=n;f.Unique=u;}

/* our handle to the pipe */
int cfs;

/* our local object: NOTE: we try to do as little as possible
 * and trust that vfs will handle caching for us */
struct v_list {
  char *real_name;
  char *local_name;
  short usage;
  char  has_changed; // dirty bit
  char  is_dir;
  char  is_created; // marker for files which do not yet exist at the other end
  char  is_trunc;   // marker for files which are to be sent to the other end
  /* timestamp ?? */
};

int count;
uid_t saved_uid;

#define STANDALONE 1
#include "tdb.h"

static TDB_CONTEXT *tdb;

#ifdef __INSURE__

#include <dlfcn.h>

extern void pstring_sub(char *s,const char *pattern,const char *insert);

/*******************************************************************
This routine is a trick to immediately catch errors when debugging
with insure. A xterm with a gdb is popped up when insure catches
a error. It is Linux specific.
********************************************************************/
int _Insure_trap_error(int a1, int a2, int a3, int a4, int a5, int a6)
{
	static int (*fn)();
	int ret;
	char pidstr[10];
	pstring cmd = "/usr/X11R6/bin/xterm -T Panic -n Panic -e /bin/sh -c 'cat /tmp/ierrs.*.%d ; gdb /proc/%d/exe %d'";

	snprintf(pidstr, sizeof(pidstr) - 1, "%d", getpid());
	pstring_sub(cmd, "%d", pidstr);

	if (!fn) {
		static void *h;
		h = dlopen("/usr/local/parasoft/insure++lite/lib.linux2/libinsure.so", RTLD_LAZY);
		fn = dlsym(h, "_Insure_trap_error");
	}

	ret = fn(a1, a2, a3, a4, a5, a6);

	system(cmd);

	return ret;
}
#endif

/******************** shutdown and timeout **********************************/
void signal_handler(int signo)
{
  exit(0);
}

void generic_stat(struct stat *st)
{
	memset(st, 0, sizeof(struct stat));

	st->st_mode = __S_IFREG | 0666;
	st->st_nlink = 1;
	st->st_blksize = 1024;
}

/************************** file name maintenance **************************/

void store_vlist_entry(ViceFid id, struct v_list *entry)
{
	TDB_DATA key, data;

	key.dsize = sizeof(Unique_t);
	key.dptr = (char *)&id.Unique;

	data.dsize = sizeof(struct v_list);
	data.dptr = (char *)entry;

	tdb_store(tdb, key, data, TDB_REPLACE);
}

struct v_list *fetch_vlist_entry(ViceFid id)
{
	TDB_DATA key, data;

	key.dsize = sizeof(Unique_t);
	key.dptr = (char *)&id.Unique;

	data = tdb_fetch(tdb, key);

	return (struct v_list *)data.dptr;
}

void delete_vlist_entry(ViceFid id)
{
	TDB_DATA key;

	key.dsize = sizeof(Unique_t);
	key.dptr = (char *)&id.Unique;

	tdb_delete(tdb, key);
}

char *look_name( ViceFid id )
{
	struct v_list *entry;
	char *real_name;

	if ((id.Volume != MY_VOL) || (id.Vnode != MY_VNODE)) {
		printf( "Bad handle passed %lx/%lx/%lx\n", id.Volume, 
			id.Vnode, id.Unique );
		exit(1);
	}

	if ((entry = fetch_vlist_entry(id))) {

		real_name = entry->real_name;
		free(entry);
		
		return real_name;
	}

	return NULL;
}

ViceFid
alloc_vfid( char *name )
{
	ViceFid res;
	static Unique_t id = 69;
	struct v_list entry;

	memset(&entry, 0, sizeof(struct v_list));
	entry.real_name = strdup(name);
	
	MK_FID(res,MY_VOL,MY_VNODE,(long)id);
	store_vlist_entry(res, &entry);

	DEBUG(("\tnew vfid %ld created for file %s\n", id, 
	       entry.real_name));

	id++;
	count++;

	return res;
}

int v_created(ViceFid id)
{
	struct v_list *entry = fetch_vlist_entry(id);
	int result = 0;

	result = entry && entry->is_created;
	if (entry) free(entry);

	return result;
}

void
delete_name(ViceFid id ) 
{
	struct v_list *entry = fetch_vlist_entry(id);

	free(entry->real_name);
	if (entry->local_name) free(entry->local_name);
	if (entry) free(entry);

	delete_vlist_entry(id);
}

int CodaToAccessFlags(int flags)
{
	int aflags = 0;

	printf("\taccess flags are: ");
	if (flags & C_A_C_OK) printf("C_A_C_OK ");
	if (flags & C_A_R_OK) printf("C_A_R_OK ");
	if (flags & C_A_W_OK) printf("C_A_W_OK ");
	if (flags & C_A_X_OK) printf("C_A_X_OK ");
	if (flags & C_A_F_OK) printf("C_A_F_OK ");
	printf("\n");

	if (flags & C_A_C_OK) aflags |= W_OK; /* ??? */
	if (flags & C_A_R_OK) aflags |= R_OK;
	if (flags & C_A_W_OK) aflags |= W_OK;
	if (flags & C_A_X_OK) aflags |= X_OK;
	if (flags & C_A_F_OK) aflags |= F_OK;

	return aflags;
}

inline int
CodaToOpenFlags( int flags )
{
	int oflags = 0;

	printf("\topen flags are: ");
	if (flags & C_O_READ) printf("C_O_READ ");
	if (flags & C_O_WRITE) printf("C_O_WRITE ");
	if (flags & C_O_TRUNC) printf("C_O_TRUNC ");
	if (flags & C_O_CREAT) printf("C_O_CREAT ");
	if (flags & C_O_EXCL) printf("C_O_EXCL");
	printf("\n");

	/* Set read/write flags */

	switch (flags & (C_O_READ | C_O_WRITE)) {
	case (C_O_READ | C_O_WRITE):
		oflags |= O_RDWR;
		break;
	case C_O_READ:
		oflags |= O_RDONLY; 
		break;
	case C_O_WRITE:
		oflags |= O_WRONLY;
		break;
	}

	if (flags & C_O_TRUNC) {
		oflags |= O_TRUNC;
	}

	if (flags & C_O_CREAT) {
		oflags |= O_CREAT;
	}

	return oflags;
}

char *smbw_getlocalcopy(char *remote_name, char *local_name)
{
    char *tmp, *result = NULL;
    int fdin = -1, fdout = -1, i;
    char buffer[8192];
    struct stat mystat;

    fdin = smbw_open (remote_name, O_RDONLY|O_CREAT, 0600);
    if (fdin == -1) {
	    return NULL;
    }

    tmp = local_name ? local_name : tempnam(NULL, "pfr");

    fdout = open (tmp, O_CREAT|O_WRONLY|O_TRUNC, 0600);

    if (fdout == -1) {
	    goto fail;
    }

    while ((i = smbw_read (fdin, buffer, sizeof (buffer))) > 0){
	    if (write (fdout, buffer, i) != i) {
		    goto fail;
	    }
    }

    if (i == -1) {
	    goto fail;
    }

    i = smbw_close (fdin);
    fdin = -1;

    if (i==-1) {
	    goto fail;
    }

    if (close (fdout)==-1) {
	    goto fail;
    }

    if (smbw_stat (remote_name, &mystat) != -1){
        chmod (tmp, mystat.st_mode);
    }

    result = tmp;

 fail:
    if (fdout != -1) close(fdout);
    if (fdin != -1) smbw_close (fdin);

    return result;
}

/*********************local copy management ********************************/
inline char *
get_local_copy( ViceFid id, int flags )
{
  struct v_list* v = fetch_vlist_entry(id);
  char *name;

  /* I would normally put an assert here, but look_name() was called already */
  /* truncated files do not need an ftp read first; this code cluster handles it */

  v->is_created = 0;
  if (flags & C_O_WRITE)
    v->has_changed = 1;
  if (flags & C_O_TRUNC) {
	  int fd;

	  v->is_trunc = 1;
	  if (!v->local_name) {
		  v->local_name = tempnam( NULL, "pfl" );
	  }

	  fd = open(v->local_name, O_WRONLY | O_TRUNC | O_CREAT, 0666);
	  close(fd);

	  printf("\topening truncated file %s as %s\n", v->real_name, 
		 v->local_name);
  } else {
	  v->local_name = smbw_getlocalcopy(v->real_name, v->local_name); /* fetch from other end */
	  printf("\tcopying remote file %s to %s\n", v->real_name, v->local_name);
  }

    name = v->local_name;
    store_vlist_entry(id, v);
    free(v);
    return name;
}

void
write_dir_entry( int handle, char *name )
{
  struct venus_dirent ent;
  int len;
  static int ino = MY_INODE;
  
  ent.d_fileno = ino++;
  ent.d_type = CDT_REG; /* the kernel does not use this */
  
  ent.d_namlen = len = strlen(name);
  strcpy(ent.d_name, name);
  len += ((char *) &ent.d_name - (char *) &ent);
  ent.d_reclen = len;
  if (write(handle, &ent, len)<0)
    printf( "error writing dirent (%s)\n", strerror(errno));   /* FIXME: we should propagate error */
}

char *get_dir_copy( ViceFid id )
{
	struct v_list* v = fetch_vlist_entry(id);
  DIR *dir;
  char *cache;
  int handle;
  struct dirent *ent1;
  char zeros[128] = {0,0, };
  char *result = NULL;

  dir = smbw_opendir(v->real_name);

  if (!dir) goto done;

  v->is_dir = 1;
  cache = tempnam (NULL, "dir");
  handle = open (cache, O_WRONLY | O_CREAT | O_EXCL, 0600);
  if (handle == -1) {
    printf("can not open temp file for directory list (%s)\n", strerror(errno));
    smbw_closedir(dir);
    free(cache);
    goto done;
  }

  printf("\topening directory listing file %s\n", cache);

  /* copy a list file names out to a file */
  while ((ent1 = smbw_readdir(dir)))
     write_dir_entry(handle, ent1->d_name);
  write(handle, zeros, 2);
  close(handle);
  smbw_closedir(dir);
  v->local_name = cache;
  result = cache;

 done:
  store_vlist_entry(id, v);
  free(v);
  return result;
}

int unget_local_copy( ViceFid id )
{
	struct v_list *v = fetch_vlist_entry(id);
	int result = 0;

  if (v->local_name) {
    if (!v->is_dir && (v->is_trunc || v->has_changed)) {
              /* mc_filecopy() */
      int hw;
      int hr = open(v->local_name, O_RDONLY);

      printf("\tcopying local file %s to %s\n", v->local_name, v->real_name);

      if (hr == -1) {
	      printf("\t**local open failed\n");
	      goto done;
      }

      hw  = smbw_open(v->real_name, O_WRONLY | O_CREAT | O_TRUNC, 0666);

      if (hw == -1) {
	      printf("\t** remove open failed\n");
	      close(hr);
	      goto done;
      }

      if (hw>=0 && hr>=0) {
        char *p = malloc(0x4000);
        int n = 0x4000;
        while (n>0) {
          n = read(hr,p,n);
          if (n>0) n = smbw_write(hw,p,n);
        }
        smbw_close(hw);
        close(hr);
        free(p);
        v->is_trunc = 0;
      }
    }
    v->has_changed = 0;
    printf("\tunlinking local file %s\n", v->local_name);
    unlink(v->local_name); 
    free(v->local_name);
    v->local_name = NULL;
  } else {
    DEBUG(( "<empty file name on a close>" ));
  }

  result = 1;

 done:

  store_vlist_entry(id, v);
  free(v);

  if (result == 0) printf("\tcopy FAILED\n");
  return result;
}

/****************** attribute mangling *************************************/
inline int
st2type(struct stat *s)
{
  if (S_ISDIR(s->st_mode))
    return C_VDIR;
  if (S_ISREG(s->st_mode))
    return C_VREG;
  if (S_ISBLK(s->st_mode))
    return C_VBLK;
  if (S_ISCHR(s->st_mode))
    return C_VCHR;
  if (S_ISLNK(s->st_mode))
    return C_VLNK;
  if (S_ISSOCK(s->st_mode))
    return C_VSOCK;
  if (S_ISFIFO(s->st_mode))
    return C_VFIFO;
  printf( "Unknown type in st2type (%o)\n", s->st_mode );
  return C_VNON;
}

void
st2attr(struct stat *s, struct coda_vattr *a)
{
  static int id = 0;

  bzero(a, sizeof(struct coda_vattr));
  a->va_type = st2type(s);
#define COPY(x) a->va_##x = s->st_##x;
  COPY(mode);
  COPY(nlink);
  COPY(uid);
  COPY(gid);
  a->va_fileid = id++;
  COPY(size);
  a->va_blocksize = 1024; /* s->st_blksize; */
  a->va_atime.tv_nsec = a->va_ctime.tv_nsec = a->va_mtime.tv_nsec = 0;
  a->va_atime.tv_sec = s->st_atime;
  a->va_mtime.tv_sec = s->st_mtime;
  a->va_ctime.tv_sec = s->st_ctime;
  a->va_gen = 0;
  a->va_flags = 0;

  a->va_bytes = s->st_blocks * s->st_blksize;
  a->va_filerev = 0;

}

/* Poor protection against deadlocks when podfuk is mounted on
   /smb (right protection is VFS_NO_LOCALHASH, which is
   unfortunately in new midnights, only). 

   In fact, "new midnight" currently means my own tree at my home
   machine :-) */
int 
legal_name(char *name)
{
	if (!strncmp (name, MOUNT_POINT_STRING, strlen(MOUNT_POINT_STRING))
		== 0)
		return 0;
	return 1;
}

/* Retrieve authentication information from podfuk-authd */

static void podfuk_get_auth_data(char *server, char *share, char **workgroup,
				 char **username, char **password)
{
	struct auth_token token;

	fprintf(stderr, ">>> getting auth data for %s\\%s\n",
		server, share);

	/* Try fetching authentication info for \\server\share, then
	   \\server then \\ for the default user. */

	if (fetch_token(saved_uid, server, share, &token) || 
	    fetch_token(saved_uid, server, NULL, &token) ||
	    fetch_token(saved_uid, NULL, NULL, &token)) {

		*workgroup = strdup(token.workgroup);
		*username = strdup(token.username);
		*password = strdup(token.password);

		goto done;
	}

	/* Not found, try to connect anonymously */

	*username = "";
	*workgroup = lp_workgroup();
	*password = "";

 done:
	fprintf(stderr, ">>> got %s\\%s %s\n", *workgroup, *username, 
		*password);
}

/* Print out usage information */

static void podfuk_usage(void)
{
	printf("Usage: podfuk-smb [options]\n\n");
	printf(" -s config file\t\tSpecify alternate config file\n");
	printf(" -W workgroup\t\tSpecify workgroup name\n");
	printf(" -d value\t\tSet debug level to value\n");
	printf(" -c device file\t\tSpecify device to open, default /dev/cfs0\n");
	printf(" -h\t\t\tPrint usage information\n");
	exit(0);
}

int
main(int argc, char** argv)
{
  char buf[2048];
  time_t time_last_msg = (time_t) 0x7fffffff;
  pstring cfs_file;

  strcpy(cfs_file, "/dev/cfs0");

  /* smbw initialisation */

  {
	  extern FILE *dbf;
	  int opt;
	  pstring servicesf;

	  dbf = stdout;

	  snprintf(servicesf, sizeof(pstring) - 1, "%s/podfuk-smb.conf",
		   LIBDIR);
	  servicesf[sizeof(pstring)] = '\0';

	  smbw_setup_shared();

	  /* Parse command line options */
	  
	  while ((opt = getopt(argc, argv, "W:d:hs:c:")) != EOF) {
		switch (opt) {
		case 'W':
			smbw_setshared("WORKGROUP", optarg);
			break;
		case 'd':
			smbw_setshared("DEBUG", optarg);
			break;
		case 's':
			strncpy(servicesf, optarg, sizeof(pstring) - 1);
			servicesf[sizeof(pstring)] = '\0';
			break;
		case 'c':
			strncpy(cfs_file, optarg, sizeof(pstring) - 1);
			cfs_file[sizeof(pstring)] = '\0';
			break;
		case 'h':
		default:
			podfuk_usage();
		}
	  }

	  charset_initialise();

	  /* Load podfuk-smb.conf file */

	  smbw_setshared("SERVICESF", servicesf);
	  lp_load(servicesf, True, False, False);

	  codepage_initialise(lp_client_code_page());

	  /* Initialise callback to fetch authentication data */

	  smbw_set_auth_data_fn(podfuk_get_auth_data);
	  
	  /* Initialise vfid tdb */

	  if (!(tdb = tdb_open("", 0, TDB_NOLOCK | TDB_INTERNAL,
			       O_RDWR | O_CREAT, 0600))) {
		  fprintf(stderr, "unable to open vfid cache %s\n",
			  strerror(errno));
		  exit(1);
	  }
  }

  setvbuf(stdout, NULL, _IONBF, 0);
#ifndef NODAEMON
  chdir("/");
  if (fork()) {
    exit(0);
  }
  setsid(); /* to guarantee effect, the man page says this should be performed after
	       a fork, as the child... */
  DEBUG(("podfuk spawned as %d, ", getpid()));
#endif
  cfs = open(cfs_file, O_RDWR );	/* We need to go daemon, first, then to open cfs, otherwise coda will break */
  if (cfs == -1) {
    printf( "Error opening %s: %s\n", cfs_file, strerror(errno));
    exit(1);
  } 
  DEBUG(("Opened %s\n", cfs_file));
  
  signal(SIGTERM, signal_handler); /* graceful shutdown */
  signal(SIGINT,  signal_handler);
  signal(SIGPIPE, SIG_IGN);     /* pipe faults are benign */

  while(1) {
      /* NOTE: both the inbuf/req and the outbuf/rep must be bigger than
       * just the union given in coda.h
       */
    char in_buf[sizeof(union inputArgs) + CODA_MAXNAMLEN];
    union inputArgs *req = (union inputArgs*) &in_buf[0];
    char out_buf[sizeof(union outputArgs) + CODA_MAXNAMLEN];
    union outputArgs *rep = (union outputArgs*) &out_buf[0];
    struct stat st;
    int msg;
    int size;
    char *name;
    fd_set rfds;
    struct timeval tv;
    int retval;

    /* Watch stdin (fd 0) to see when it has input. */
    FD_ZERO(&rfds);
    FD_SET(cfs, &rfds);

    /* Wait up to five seconds. */
    tv.tv_sec = 5;
    tv.tv_usec = 0;

    retval = select(cfs+1, &rfds, NULL, NULL, &tv);
    /* onError */
    if (retval == -1) {
      printf( "select failed: %s\n", strerror(errno));
      exit(1);
    }
#if 0
    /* There are some problems, somewhere. Lets take a look */
    if (retval == 0) {
        if (time(NULL)-time_last_msg > FLUSH_TIME) {
          flush_VFids();
          time_last_msg = (time_t) 0x7fffffff; /* only flush once */
        }
    }
#endif
    
    /* Don't rely on the value of tv now! */
    
    msg = read(cfs, req, sizeof(*req) + CODA_MAXNAMLEN);
    if (msg == -1)
        continue;

    DEBUG(("got opcode = %2.2ld ", req->ih.opcode ));

    setfsgid (req->ih.cred.cr_fsgid);
    setfsuid (req->ih.cred.cr_fsuid);

    saved_uid = req->ih.cred.cr_fsuid;

    rep->oh.opcode = req->ih.opcode;
    rep->oh.unique = req->ih.unique;
    rep->oh.result = ENOSYS;
    size = sizeof(rep->oh);

#define CMD(x) rep->oh.result = 0; size = sizeof(rep->coda_##x);
#define CMD_NOREP(x) rep->oh.result = 0;

//#define DUMP(x) DEBUG_PRINT( "(%x/%x/%x:%s)", req->coda_##x.VFid.Volume, req->coda_##x.VFid.Vnode, req->coda_##x.VFid.Unique, look_name(req->coda_##x.VFid));
#define DUMP(x) DEBUG_PRINT( "\n\tbase:%s\n\t", look_name(req->coda_##x.VFid));
#define DUMP_NAME(x) DEBUG_PRINT( "\n\tbase:%s\tname:%s\n\t", look_name(req->coda_##x.VFid), (char*)req + req->coda_##x.name);
#define STAT(x) if (!legal_name(x)) {rep->oh.result = ENOENT; break; } else {if (smbw_stat(x, &st) == -1) { rep->oh.result = ERRNO; break; } st.st_uid = req->ih.cred.cr_fsuid; st.st_gid = req->ih.cred.cr_fsgid;}
#define BUILD_NAME(x) name = ((char*) req) + req->coda_##x.name; sprintf( buf, "%s/%s", look_name(req->coda_##x.VFid), name);
#define GET_VFID_name(x) if (NULL==(name=look_name(req->coda_##x.VFid))) {rep->oh.result = ENOENT;  break;}
    
    switch (req->ih.opcode) {

	    /* Create a parent directory */

    case CODA_ROOT: {
	    struct v_list *entry;

	    CMD(root);
	    DEBUG(("CODA_ROOT\n"));

	    rep->coda_root.VFid = alloc_vfid(MOUNT_POINT_STRING);

	    entry = fetch_vlist_entry(rep->coda_root.VFid);
	    entry->usage = 1;
	    store_vlist_entry(rep->coda_root.VFid, entry);
	    free(entry);

	    break;
    }

      /********************* file props & access *******************/

    case CODA_GETATTR: {
	    struct v_list *entry;

	    entry = fetch_vlist_entry(req->coda_getattr.VFid);

	    CMD(getattr); 
	    DEBUG(("CODA_GETATTR %s\n", entry->real_name));
	    
	    GET_VFID_name(getattr);

	    if (!entry->is_created) {
		    STAT(name); /* fills in st */
	    } else {
		    if (stat(entry->local_name, &st) == -1) {
			    rep->oh.result = ERRNO;
		    }
	    }
	    
	    st2attr( &st, &rep->coda_getattr.attr );

	    break;
    }

    case CODA_SETATTR:
	    CMD_NOREP(setattr);
	    DEBUG(("CODA_SETATTR %s\n", look_name(req->coda_setattr.VFid)));

      GET_VFID_name(setattr);
      if ( req->coda_setattr.attr.va_mode != (u_short) -1) {
	      if (smbw_chmod( name, req->coda_setattr.attr.va_mode ) == -1)
	      {
		      rep->oh.result = ERRNO;
	      }
      }
      /* cannot change owner, group or dates .......*/
      break;

    case CODA_ACCESS: {
	    struct v_list *entry;
	    int aflags;

	    /* This always returns TRUE; this seems to be ok with current
               CODA design */

	    CMD_NOREP(access);
	    DEBUG(("CODA_ACCESS %s\n", look_name(req->coda_access.VFid)));

	    GET_VFID_name(access);

	    if ((entry = fetch_vlist_entry(req->coda_access.VFid))) {
		    aflags = CodaToAccessFlags(req->coda_access.flags);
		    printf("\tcalling access on %s\n", name);

		    if (smbw_access(name, aflags) == -1) {
			    smbw_access(name, aflags);
			    rep->oh.result = ERRNO;
		    }
	    }

	    break;
    }

    case CODA_LOOKUP: /* !! ttd: search for existing VFid's instead of making many new ones */
	    GET_VFID_name(lookup);

	    BUILD_NAME(lookup);

	    CMD(lookup);
	    DEBUG(("CODA_LOOKUP %s\n", buf));

	    STAT(buf); /* fills in st */
	    rep->coda_lookup.VFid = alloc_vfid(buf);
	    rep->coda_lookup.vtype = st2type(&st);
      break;

      /* Readlink removed as smb doesn't have links */

/*    case CODA_READLINK: */

      /************************ open, close, create & mkdir ******************/
    case CODA_OPEN: {
	    struct v_list *entry;

	    CMD(open); 
	    DEBUG(("CODA_OPEN %s\n", look_name(req->coda_open.VFid)));

	    GET_VFID_name(open);
	    if (!v_created(req->coda_open.VFid)) {
		    STAT(name);
	    } else {
		    /* Open of non-existent file */
		    generic_stat(&st); /* XXX file perms? */
	    }
	    if (S_ISDIR(st.st_mode)) {
		    name = get_dir_copy(req->coda_open.VFid);
	    } else {
		    name = get_local_copy(req->coda_open.VFid,
					  req->coda_open.flags);
	    }
	    
	    if (!name || (stat(name, &st)==-1)) {
		    rep->oh.result = ERRNO;
		    if (!name) free(name);
		    break;
	    }
	    
	    entry = fetch_vlist_entry(req->coda_open.VFid);
	    entry->usage += 1;
	    entry->local_name = name;
	    store_vlist_entry(req->coda_open.VFid, entry);
	    free(entry);
	    
	    rep->coda_open.dev = st.st_dev;
	    rep->coda_open.inode = st.st_ino;
	    break;
    }

    case CODA_CLOSE: {
	    struct v_list *entry;

	    CMD_NOREP(close);
	    DEBUG(("CODA_CLOSE %s\n", look_name(req->coda_close.VFid)));

	    GET_VFID_name(close);
	    if (!unget_local_copy(req->coda_close.VFid)) {
		    rep->oh.result = ERRNO;
	    }
	    
	    entry = fetch_vlist_entry(req->coda_close.VFid);
	    entry->usage -= 1;
	    store_vlist_entry(req->coda_close.VFid, entry);

	    free(entry);
	    
	    break;
    }

    case CODA_CREATE: {
	    int fd;

	    GET_VFID_name(create);
	    BUILD_NAME(create);

	    CMD(create);
	    DEBUG(("CODA_CREATE %s\n", buf));

	    rep->coda_create.VFid = alloc_vfid(buf);

	    /* Touch the file */

	    fd = smbw_open(buf, O_WRONLY | O_CREAT | (req->coda_create.excl ?
						      O_EXCL : 0),
			   req->coda_create.mode);

	    if (fd == -1) {
		    printf("\terror creating remote file: %s\n",
			   strerror(errno));
		    rep->oh.result = ERRNO;
	    } else {
		    smbw_close(fd);
	    }

	    rep->coda_create.attr = req->coda_create.attr;
	    break;
    }

    case CODA_MKDIR:
	    CMD(mkdir);
	    DEBUG(("CODA_MKDIR %s\n", look_name(req->coda_mkdir.VFid)));

	    GET_VFID_name(mkdir);
	    BUILD_NAME(mkdir);
	    
	    if ( smbw_mkdir(buf, req->coda_mkdir.attr.va_mode ) == 0) {
		    rep->coda_mkdir.VFid = alloc_vfid(buf);
		    rep->coda_mkdir.attr = req->coda_mkdir.attr;
	    } else
		    rep->oh.result = ERRNO;
	    break;

      /********************* deletions & rename ******************/

    case CODA_RMDIR:
	    CMD_NOREP(rmdir);

	    GET_VFID_name(rmdir);
	    BUILD_NAME(rmdir);

	    DEBUG(("CODA_RMDIR %s\n", buf));

	    if ( smbw_rmdir( buf ) == 0) {
		    rep->oh.result = 0;
//        delete_name(req->coda_rmdir.VFid);
	    } else
		    rep->oh.result = ERRNO;
	    break;

    case CODA_REMOVE:

      GET_VFID_name(remove);
      BUILD_NAME(remove);

      CMD_NOREP(remove);
      DEBUG(("CODA_REMOVE %s\n", buf));

      printf("\tunlinking remote file %s\n", buf);

      if ( smbw_unlink( buf ) == 0) {
	      struct v_list *entry;

	      entry = fetch_vlist_entry(req->coda_remove.VFid);

	      if (entry->local_name) {
		      unlink(entry->local_name);
		      printf("\tremoving local file %s\n", entry->local_name);
		      free(entry->local_name);
		      entry->local_name = NULL;
		      store_vlist_entry(req->coda_remove.VFid, entry);
	      }
	      rep->oh.result = 0;
      } else {
	      printf("\terror %s\n", strerror(errno));
	      rep->oh.result = ERRNO;
      }
      break;

    case CODA_RENAME:
	    CMD_NOREP(rename);
	    DEBUG(("CODA_RENAME\n"));

      {
        char buf2[256];
        name = ((char *) req) + req->coda_rename.srcname;
        if (!name) {
          rep->oh.result = ENOENT;
          break;
        }
        sprintf( buf, "%s/%s", look_name(req->coda_rename.sourceFid), name );
        name = ((char *) req) + req->coda_rename.destname;
        sprintf( buf2, "%s/%s", look_name(req->coda_rename.destFid), name );
        DEBUG(("src name=%s, dest name %s: ", buf, buf2 ));
        if ( smbw_rename(buf, buf2) == 0) {
          rep->oh.result = 0;
//          delete_name(req->coda_rename.sourceFid);
        } else
          rep->oh.result = ERRNO;
      }
      break;

      /* Return file system statistics.  Just return zeros as we can't
	 calculate any reasonable figures. */

    case CODA_STATFS:
	    CMD(statfs);
	    DEBUG(("CODA_STATFS\n"));

	    rep->oh.result = 0;
	    rep->coda_statfs.stat.f_blocks = 0;
	    rep->coda_statfs.stat.f_bfree = 0;
	    rep->coda_statfs.stat.f_bavail = 0;
	    rep->coda_statfs.stat.f_files = 0;
	    rep->coda_statfs.stat.f_ffree = 0;
	    break;

    default:
      DEBUG(("\tunimplemented coda call %ld\n", req->ih.opcode));
      break;
    }

    if (rep->oh.result) {
	    DEBUG(("\treturning FAILURE\n"));
    }

    msg = write(cfs, rep, size);
    fflush(stdout);

    setegid (0);
    seteuid (0);

    time_last_msg = time(NULL);
  } /* while */
}
