/*
 * parseconfig.c
 *
 * Copyright (C) 1993, 1994 Alain Knaff
 */
#define _LARGEFILE64_SOURCE
#define _GNU_SOURCE

#include "sysincludes.h"


#define BUFLEN 1024
#define MAX_FA_SIZE 100

#define TK_NONE 0
#define TK_STRING 1
#define TK_COMMANDS 2
#define TK_USE 3
#define TK_CLASS 4 /* begin of a class definition */
#define TK_END 5
#define TK_DEFAULT 6
#define TK_NO_TOKEN 7
#define TK_EOL 8

#define TOK_VALUE 0xfff
#define TOK_PREFIX (~TOK_VALUE)

#define FA_BASE 0x1000
#define CM_BASE 0x2000
#define NCM_BASE 0x3000
#define PM_BASE 0x4000

#define TK_CM(a) ( CM_BASE | (a) )
#define TK_NCM(a) ( NCM_BASE | (a) )
#define TK_FA(a) ( FA_BASE | (a) )
#define TK_PM(a) ( PM_BASE | (a) )

static struct token_table {
  char *name;
  int value;
} token_table[]={
  { "commands", TK_COMMANDS },
  { "command", TK_COMMANDS },
  { "use", TK_USE },
  { "uses", TK_USE },
  { "class", TK_CLASS },
  { "end", TK_END },
  { "default", TK_DEFAULT },

  { "all", TK_FA( FA_ALL2) },
  { "dir", TK_FA( FA_DIR) },
  { "directory", TK_FA( FA_DIR) },
  { "subdir", TK_FA (FA_SUBDIR) },
  { "subdirectory", TK_FA (FA_SUBDIR) },
  { "basename", TK_FA ( FA_BASENAME) },
  { "suffix", TK_FA ( FA_SUFFIX) },
  { "filename", TK_FA ( FA_FILENAME) },
  { "filesystem", TK_FA ( FA_FS) },

  { "use_tmp_file", TK_PM(  PM_USE_TMP_FILE ) },
  { "hide_pipe", TK_PM( PM_HIDE_PIPE ) },
  { "use_and_hide_pipe", TK_PM( PM_HIDE_PIPE ) },
  { "show_pipe", TK_PM ( PM_SHOW_PIPE ) },
  { "use_and_show_pipe", TK_PM ( PM_SHOW_PIPE ) },
  { "dir_leave_compressed", TK_PM ( PM_DIR_LEAVE_COMPR ) },
  { "leave_compressed", TK_PM ( PM_LEAVE_COMPR ) },

  { "create_compressed", TK_PM(PM_CREATE_COMPR) },
  { "no_create_compressed", TK_PM(PM_NOCREATE_COMPR) },

  { "append_compressed", TK_PM(PM_APPEND_COMPR) },
  { "no_append_compressed", TK_PM(PM_NOAPPEND_COMPR) },

  { "uncompress_before_write", TK_PM(PM_NO_UNCOMPR_BEFORE_WRITE) },
  { "no_uncompress_before_write", TK_PM(PM_UNCOMPR_BEFORE_WRITE) },

  { "show_compressed_size", TK_PM(PM_SIZE_COMPR) },
  { "show_uncompressed_size", TK_PM(PM_SIZE_UNCOMPR) },

  { "disable", TK_CM ( CM_DISAB ) },
  { "disable_child", TK_CM ( CM_DISAB_CHILD ) },
  { "readdir_compr", TK_CM ( CM_READDIR_COMPR ) },
  { "readdir", TK_CM ( CM_READDIR_COMPR ) },
  { "verbose", TK_CM ( CM_VERBOSE ) },
  { "unlink",  TK_CM ( CM_UNLINK ) },

  { "enable", TK_NCM ( CM_DISAB ) },
  { "enable_child", TK_CM ( CM_DISAB_CHILD ) },
  { "readdir_uncompr", TK_NCM ( CM_READDIR_COMPR ) },
  { "silent", TK_NCM ( CM_VERBOSE ) },
  { "no_unlink",  TK_NCM ( CM_UNLINK ) },

  { 0, TK_NO_TOKEN } };


#define E_NOT_FOUND 0
#define E_EXP_STR -1
#define E_EXP_FA -2
#define E_EXP_PM -3
#define E_EXP_EOL -4
#define E_SHORT -5
#define E_BAD_TOK -6 
#define E_OOM -7
#define E_FA_TOO_BIG -8
#define E_EOF_REACHED -9
#define E_COM_FOL_FA -10
#define E_NO_CLASS -11
#define E_TWICE -12

#ifndef CONFIG_COMPILER
static
#endif
char *err_strings[]={
  "Record not found",
  "String expected",
  "File action expected",
  "Pipe mode expected",
  "End of line expected",
  "End of line reached",
  "Bad token",
  "Out of memory",
  "Too many filename actions",
  "End of file reached",
  "Commands clause following file-actions clause",
  "Undefined command class",
  "Same command listed twice"
};

static char *mystrsep(char **stringp, const char *delim)
{
    char *sp;
    const char *dp;

    sp = *stringp;
    if(!sp || !*sp)
	return 0;
    while(**stringp) {
	for(dp=delim; *dp; dp++)
	    if(*dp == **stringp) {
		**stringp = '\0';
		(*stringp)++;
		return sp;
	    }
	(*stringp)++;
    }
    return sp;
}


static char *mymalloc(size_t size)
{
  /* lightweight malloc. Avoids memory allocation in low level layers. */
  static char buffer[256];
  static int offset=0;
  char *ptr;

  if ( offset + size > 256 )
    return (char *)malloc(size);
  ptr = buffer+offset;
  offset += size;
  return ptr;
}
  
static int my_strcmp(char *pattern, char *tok)
{
  while(1){
    if (! *pattern && ! *tok)
      return 0;
    if (*pattern == *tok){
      tok++;
      pattern++;
      continue;
    }
    if (*pattern == '-' || *pattern == '_'){
      if (*tok == '-' || *tok == '_')
	tok++;
      pattern++;
      continue;
    }
    return 1;
  }
}

static int get_next_token(char **stringp, char **val)
{
  int stringmode;
  struct token_table *tok;
  char *delim;

  while(1) {
    if (! *stringp  )
      return TK_EOL;
    switch ( **stringp ){
    case '#':
      return TK_EOL;
    case '"':
      stringmode = 1;
      (*stringp)++;
      delim= "\"\n";
      break;
    case '\'':
      stringmode = 1;
      (*stringp)++;
      delim = "\'\n";
      break;
    default:
      stringmode = 0;
      delim = "\n\t;, #";
    }

    *val = mystrsep( stringp, delim ) ;
    if ( *val == 0 )
      return TK_EOL;
    
    if ( **val == 0 )
      continue;

    if ( !stringmode ){
      tok = token_table;
      while ( tok->name && my_strcmp( tok->name, *val ) )
	tok++;
      return tok->value;
    } 
    return TK_STRING;
  }
}

static int parse_commands_line(char *prgname, 
			       char *stringp, 
			       char *class, 
			       int *mode,
			       int *modemask)
{
  int have_found;
  char *string;
  int tok;
  int stop_loop;
#ifdef CONFIG_COMPILER
  int ret;
  commands_line *ptr;
  commands_line *cmd;

  cmd = 0;
  generation++;
#endif 

  have_found = 0;
  stop_loop = 0;

  while( ! stop_loop ){    
    switch( tok = get_next_token( & stringp, & string) ){
    case TK_STRING:
#ifdef CONFIG_COMPILER
      have_found = 1;
      if((ret=add_prog(&cmd,string)))
	return ret;
#else
      if ( strcmp( string, prgname) == 0 ) 
	have_found = 1;
#endif
      break;
    case TK_DEFAULT:
#ifdef CONFIG_COMPILER
      if((ret=add_default(&cmd)))
	return ret;
#endif
      have_found = 1;
      break;
    case TK_USE:
      if (!have_found ) 
	return 0;
      stop_loop = 1;
      break;
    case TK_EOL:
      return E_EXP_EOL;
    default:
      return E_BAD_TOK;      
    }
  }

  while ( 1 ){
    switch( tok = get_next_token( & stringp, & string) ){
    case TK_STRING:
#ifndef CONFIG_COMPILER
      if ( class[0] == '\0' )
	strncpy( class, string, 16 );
#else
      for(ptr=cmd; ptr; ptr = ptr->localnext)
	if ( !ptr->class[0])
	  strncpy(ptr->class, string,16);
#endif
      break;
    case TK_EOL:
      return 0;
    default:
      if ( (tok & ~TOK_VALUE) == CM_BASE ){
#ifdef CONFIG_COMPILER
	for(ptr=cmd; ptr; ptr = ptr->localnext)
	  ptr->mode |= ( tok & TOK_VALUE ) & ~ptr->modemask;
#else
	*mode |= ( tok & TOK_VALUE ) & ~*modemask;
#endif
      } else if ((tok & ~TOK_VALUE) == NCM_BASE) {
#ifdef CONFIG_COMPILER
	for(ptr=cmd; ptr; ptr = ptr->localnext)
	  ptr->modemask |= tok & TOK_VALUE;
#else
	*modemask |= tok & TOK_VALUE;
#endif
      } else
	return E_BAD_TOK;
      break;
    }
  }
}


#ifdef CONFIG_COMPILER
#define ___zlibc_nativestat(name,buf) stat(name,buf)
#else
#include "stat.h"
#endif

static int parse_fa_line(char *stringp, FilenameActions *fa )
{
  int have_found;
  char *string;
  int tok1, tok2, tok3;
  int stop_loop;
  int len=0;

  have_found = 0;
  stop_loop = 0;

  tok1 = tok2 = tok3 = TK_NONE;

  tok1 = get_next_token( & stringp, & string);
  if ( tok1 == TK_EOL)
    return 2;

  if ( ( tok1 & ~TOK_VALUE ) == PM_BASE ){
    tok3 = tok1;
    tok2 = TK_STRING;
    tok1 = TK_FA ( FA_ALL );
    if ( !fa )
      return 1;
  }

  if ( tok1 == TK_DEFAULT ) {
    tok2 = TK_STRING;
    tok1 = TK_FA ( FA_ALL );
    if ( !fa )
      return 1;
  }
  
  if ( tok1 == TK_FA(FA_ALL2))
    tok2 = TK_STRING;

  if ( !fa )
    return 0;

  if ( tok1 == TK_STRING ){
    tok2 = tok1;
    len = strlen ( string );

    if ( string[0] == '.' )
      tok1 = TK_FA ( FA_SUFFIX );
    else if ( string[0] == '/' ){
      if ( string[ len - 1] == '/' )
	tok1 = TK_FA (FA_SUBDIR );
      else
	tok1 = TK_FA ( FA_FILENAME);
    }
    else
      tok1 = TK_FA ( FA_BASENAME );
  }

  if ( ( tok1 & ~TOK_VALUE ) != FA_BASE )
    return E_EXP_FA;

  if ( tok2 == TK_NONE ){
    tok2 = get_next_token( & stringp, & string);
    if ( tok2 != TK_STRING )
      return E_EXP_STR;
    /* copy it */
    len = strlen (string );
  }

  fa->fa_type = tok1 & TOK_VALUE;
  fa->is_initialized = 0;

  if (tok1 != TK_FA (FA_ALL) && tok1 != TK_FA(FA_ALL2)){
    if ( tok1 == TK_FA ( FA_SUBDIR ) || tok1 == TK_FA (FA_DIR ) ) {
      /* add a trailing slash if necessary */
      if ( string[len-1] != '/' ){
	string[len]= '/'; /* overwrite the trailing 0 character */
	len++;
      }
    }

    if (tok1 != TK_FA( FA_FS)){
      fa->name = (char *)mymalloc ( len + 1);
      if ( fa->name == 0 )
	return E_OOM;

      fa->namelength = len;
      strncpy( fa->name, string, len  );
      fa->name[len]='\0';
    } else {
      struct stat buf;
      int st;
      int olderrno;
      
      olderrno = errno;
      st = ___zlibc_nativestat(string, &buf);
      errno = olderrno;

      if (st==0){
	fa->dev = buf.st_dev;
	if(strcmp(string,"/")){
	  char tmp[MAXPATHLEN+4];
	  strcpy(tmp, string);
	  strcat(tmp, "/..");
	  st = ___zlibc_nativestat(tmp, &buf );
	  if (st < 0 || buf.st_dev == fa->dev)
	    fa->namelength = 0;
	} 
      } else
	fa->dev = 0;
    }
  }

  if ( !tok3 ){
    tok3 = get_next_token( & stringp, & string);
    if ( (tok3 & ~TOK_VALUE) != PM_BASE )
      return E_EXP_PM;
  }

  fa->pipe_mode = tok3 & TOK_VALUE ;

  if ( get_next_token (  & stringp, & string) != TK_EOL )
    return E_EXP_EOL;

  if (fa->fa_type == FA_ALL)
    return 1;
  return 0;
}



static FilenameActions userFilenameActions[MAX_FA_SIZE];

#define ST_CM 1
#define ST_FA 2


static int parse_class(FILE *f,int *line, FilenameActions *fa)
{
  char buffer[BUFLEN];
  char *stringp;
  int count;
  int ret;

  count = 0;
  while ( 1 ){
    if ( fgets( buffer, BUFLEN, f) == 0 )
      return E_EOF_REACHED;
    (*line)++;
    stringp = buffer;
    ret = parse_fa_line( buffer, fa );
    if (ret==2)
      continue;      
    if ( ret )
      return ret;
    if ( fa ){
      fa++;
      count++;
    }
    if ( count > MAX_FA_SIZE )
      return E_FA_TOO_BIG;
  }
}

#ifndef CONFIG_COMPILER
static
#endif

int parse_file(char *progname, 
		      FILE *f,
		      int *line,
		      int *mode,
		      int *modemask,
		      char *classname)
{
  char buffer[BUFLEN];
  int state=ST_CM;
  char *stringp, *string;
  int ret, tok;
  FilenameActions *fa;


  *line = 0;
  while ( 1){
    if ( fgets( buffer, BUFLEN, f) == 0 )
      return 0;

    (*line)++;

    stringp = buffer;
    tok = get_next_token (  & stringp, & string);


    if ( tok == TK_EOL )
      continue;


    if ( tok == TK_COMMANDS ){
      if ( state == ST_FA )
	return E_COM_FOL_FA;

      ret= parse_commands_line(progname, stringp, classname, mode, modemask );
      if ( ret <0)
	return ret;
      continue;
    }


    if ( tok == TK_CLASS ){
      state = ST_FA;
#ifndef CONFIG_COMPILER
      if ( classname[0] == '\0' )
	return 0;

      if ( ( classname[0] == '\0' ) || (*modemask & CM_HAVE_FA) )
	/* we have already the file actions */
	return 0;
#endif
      tok = get_next_token (  & stringp, & string);
      if ( tok != TK_STRING )
	return E_EXP_STR;

#ifndef CONFIG_COMPILER
      if ( strcmp ( string, classname ) )
	/* not equal */
	fa = 0;
      else
#endif
	fa = userFilenameActions;
      ret = parse_class(f, line, fa );
      if ( ret < 0 )
	return ret;
#ifndef CONFIG_COMPILER
      if ( fa ){
	*modemask |= CM_HAVE_FA;
	return 0;
      }
#else
      print_class(fa, string,*line);
#endif
      continue;
    }
    return E_BAD_TOK;
  }
}

extern int zlib_mode;

void zlib_getuserconf(char *progname, 
		      FilenameActions **filenameActions, 
		      int *mode, int *modemask)
{
  int line;
  int ret;
  int i;
  FILE *f;
  char classname[BUFLEN];



#ifdef HOMECONF
  char homeconffile[MAXPATHLEN + 1 + sizeof( HOMECONF )  ];

  struct passwd *pw;
  uid_t uid;
  char *homedir;
  char *username;
  int iamnotsuid;

#endif

  char *conffiles[3];
  int nconffiles=0;



#ifndef SECURITY
  conffiles[0] = getenv("LD_ZLIB_CONFFILE");
  if ( conffiles[0] )
    nconffiles++;
#endif

#ifdef HOMECONF
  uid = geteuid();
#ifndef SECURITY
  iamnotsuid = (getuid() == uid || getgid() == getegid());
#else
  iamnotsuid = 0;
#endif

  if (iamnotsuid)
    homedir = getenv ("HOME");
  else
    homedir = 0;

  /* first we call getlogin. There might be several accounts sharing one uid */
  if ( !homedir){
    pw = 0;

    if (iamnotsuid)
      username = getenv("LOGNAME");
    else
      username = 0;

    if ( !username )
      username = getlogin();

    if ( username )
      pw = getpwnam( username);

    if ( pw == 0 || pw->pw_uid != uid)
      /* if we can't getlogin, look up the pwent by uid */
      pw = getpwuid(uid);
  
    /* we might still get no entry */
    if ( pw )
      homedir = pw->pw_dir;
  }

  if ( homedir ){
    strncpy(homeconffile, homedir, MAXPATHLEN );
    homeconffile[MAXPATHLEN]='\0';
#ifdef __GNUC__
    strcat(homeconffile,"/" HOMECONF );
#else
    strcat(homeconffile,"/"  );
    strcat(homeconffile, HOMECONF );
#endif
    conffiles[ nconffiles++ ] = homeconffile;
  }
#endif
  
  conffiles[ nconffiles++] = SYSCONFDIR "/zlibc.conf";

  if ( zlib_mode & CM_VERBOSE ){    
    for ( i=0; i < nconffiles; i++ )
      fprintf(stderr,"%s\n", conffiles[i] );
  }

  /* in case there were no files */
  ret = -1;

  classname[0]='\0';

  for ( i=0; i< nconffiles; i++){
    f = fopen(conffiles[i], "r" );
    if ( f == 0 )
      continue;

    ret = parse_file(progname,f, &line, mode, modemask, classname);
    fclose(f);
    if ( ret < 0 ){
      if ( zlib_mode & CM_VERBOSE )
	fprintf(stderr,
		"zlibc: %s in line %d, file %s\n", 
		err_strings[ -ret], line, conffiles[i]);
      /* skip this file and fall back to the next one */
      continue;
    }
    if ( *modemask == CM_ALL_MODES )
      break;
  }



  if ( zlib_mode & CM_VERBOSE ){    
    i=0;
    if ( (*modemask)  & CM_HAVE_FA ){
      fprintf(stderr,"Listing class\n");
      while ( userFilenameActions[i].fa_type != FA_ALL ){
	      fprintf(stderr,"%x %d %d",
			userFilenameActions[i].fa_type,
			userFilenameActions[i].pipe_mode,
			userFilenameActions[i].namelength);		
	      if(userFilenameActions[i].name)
		      fprintf(stderr," %s",
			      userFilenameActions[i].name);
	      printf("\n");		
	      i++;
      }
    } else if ( classname[0] )
      fprintf(stderr, "Trying to use undefined class \"%s\"\n", classname);
    fprintf(stderr,"%x %d default\n",
	    userFilenameActions[i].fa_type,
	    userFilenameActions[i].pipe_mode);   
  }

  *filenameActions = userFilenameActions;
}
