/*************************************************** */
/* Rule Set Based Access Control                     */
/*                                                   */
/* Author and (c) 1999-2007: Amon Ott <ao@rsbac.org> */
/*                                                   */
/* Last modified: 26/Sep/2007                        */
/*************************************************** */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <rsbac/types.h>
#include <rsbac/getname.h>
#include <rsbac/syscalls.h>
#include <rsbac/error.h>
#include <rsbac/helpers.h>
#include <rsbac/aci_data_structures.h>
#include "nls.h"
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

const char   set_prog[] = "mac_set_trusted";
int recurse = 0;
int verbose = 0;
/* default max number of cap entries per file */
#define MAXNUM 200
int maxnum = MAXNUM;
char * filename = NULL;
rsbac_uid_t * userlist;
rsbac_time_t * ttllist;
rsbac_list_ta_number_t ta_number = 0;
char * progname;

void use(void)
    {
      printf(gettext("%s (RSBAC %s)\n***\n"), progname, VERSION);
      printf(gettext("Use: %s [-r] [-v] [-o target-file] file/dirname(s)\n"), progname);  
      printf(gettext(" -r = recurse in subdirs, -v = verbose, no symlinks followed,\n"));
      printf(gettext(" -m = set maximum length of cap entry list per file, default is %u\n"), MAXNUM);
      printf(gettext(" -o target-file = write to file, not stdout\n"));
      printf(gettext(" -N ta = transaction number (default = value of RSBAC_TA, if set, or 0)\n"));
    }

int process(char * name, FILE * tfile)
  {
    int res = 0;
    char tmp1[RSBAC_MAXNAMELEN];
    int i;
    struct stat buf;

    if(verbose)
      printf(gettext("Processing FILE/DIR '%s'\n"), name);
    res = rsbac_mac_get_f_trulist(ta_number, name, userlist, ttllist, maxnum);
    if(res<0)
      {
        if(   verbose
           || (   (errno != RSBAC_EINVALIDTARGET)
               && (errno != RSBAC_EINVALIDMODULE)
              )
          ) {
          get_error_name(tmp1,res);
          fprintf(stderr, "%s: %s\n",
                  name,
                  tmp1);
        }
      }
    else
      {
        if(verbose)
          printf("# %s: %i real caps\n", name, res);
        for(i=0;i<res;i++)
          if(ttllist[i])
            {
              rsbac_time_t now = time(NULL);

              if (RSBAC_UID_SET(userlist[i]))
                fprintf(tfile,
                        "%s -T %u FILE add \"%s\" %u/%u\n",
                        set_prog,
                        now + ttllist[i],
                        name,
                        RSBAC_UID_SET(userlist[i]),
                        RSBAC_UID_NUM(userlist[i]));
              else
                fprintf(tfile,
                        "%s -T %u FILE add \"%s\" %u\n",
                        set_prog,
                        now + ttllist[i],
                        name,
                        RSBAC_UID_NUM(userlist[i]));
            }
          else
            {
              if (RSBAC_UID_SET(userlist[i]))
                fprintf(tfile,
                        "%s FILE add \"%s\" %u/%u\n",
                        set_prog,
                        name,
                        RSBAC_UID_SET(userlist[i]),
                        RSBAC_UID_NUM(userlist[i]));
              else
                fprintf(tfile,
                        "%s FILE add \"%s\" %u\n",
                        set_prog,
                        name,
                        RSBAC_UID_NUM(userlist[i]));
            }
      }
    if(   recurse
       && !lstat(name,&buf)
       && S_ISDIR(buf.st_mode)
      )
      {
        DIR * dir_stream_p;
        struct dirent * dirent_p;
        char name2[PATH_MAX];

        if(S_ISLNK(buf.st_mode))
          return(0);
        if(!(dir_stream_p = opendir(name)))
          {
            fprintf(stderr, gettext("opendir for dir %s returned error: %s\n"),
                   name,
                   strerror(errno));
            return(-2);
          }
        while((dirent_p = readdir(dir_stream_p)))
          {
            if(   (strcmp(".",dirent_p->d_name))
               && (strcmp("..",dirent_p->d_name)) )
              {
                strcpy(name2,name);
                strcat(name2,"/");
                strcat(name2,dirent_p->d_name);
                process(name2, tfile);
              }
          }
        closedir(dir_stream_p);
      }
    return(0);
  }

int main(int argc, char ** argv)
{
  int res = 0;
  int i;
  FILE * tfile;

  locale_init();

  progname = argv[0];
  {
    char * env = getenv("RSBAC_TA");

    if(env)
      ta_number = strtoul(env,0,0);
  }
  while((argc > 1) && (argv[1][0] == '-'))
    {
      char * pos = argv[1];
      pos++;
      while(*pos)
        {
          switch(*pos)
            {
              case 'h':
                use();
                return 0;
              case 'v':
                verbose++;
                break;
              case 'm':
                if(argc > 2)
                  {
                    maxnum = strtoul(argv[2], 0, 10);
                    argc--;
                    argv++;
                  }
                else
                  fprintf(stderr, gettext("%s: missing maxnum value for parameter %c\n"), progname, *pos);
                break;
              case 'r':
                recurse=1;
                break;
              case 'o':
                if(argc > 2)
                  {
                    filename = argv[2];
                    argv++;
                    argc--;
                  }
                else
                  fprintf(stderr, gettext("%s: missing filename for parameter o\n"), progname);
                break;
              case 'N':
                if(argc > 2)
                  {
                    ta_number = strtoul(argv[2], 0, 10);
                    argc--;
                    argv++;
                  }
                else
                  {
                    fprintf(stderr, gettext("%s: missing transaction number value for parameter %c\n"), progname, *pos);
                    exit(1);
                  }
                break;
              default:
                fprintf(stderr, gettext("%s: unknown parameter %c\n"), progname, *pos);
                exit(1);
            }
          pos++;
        }
      argv++;
      argc--;
    }

  if (argc > 1)
    {
      if(!filename)
        tfile = stdout;
      else
        if (!(tfile=fopen(filename,"w")))
          {
            fprintf(stderr, gettext("opening target file returned error: %s\n"),
                    strerror(errno));
          }
      if(verbose)
        {
          printf(gettext("%s: %i targets"), progname, argc - 1);
          if(recurse)
            printf(gettext(" - recursing"));
          printf("\n");
        }
      userlist = malloc(sizeof(*userlist) * maxnum);
      ttllist = malloc(sizeof(*ttllist) * maxnum);
      if(!userlist || !ttllist)
        error_exit(-ENOMEM);
      for (i=1;i < argc;i++)
        {
          process(argv[i],tfile);
        }
      if(tfile != stdout)
        fclose(tfile);
    }
  else
    {
      printf(gettext("%s (RSBAC %s)\n***\n"), progname, VERSION);
      printf(gettext("Use: %s [-r] [-v] [-o target-file] file/dirname(s)\n"), progname);  
      printf(gettext(" -r = recurse in subdirs, -v = verbose, no symlinks followed,\n"));
      printf(gettext(" -m = set maximum length of cap entry list per file, default is %u\n"), MAXNUM);
      printf(gettext(" -o target-file = write to file, not stdout\n"));
      printf(gettext(" -N ta = transaction number (default = value of RSBAC_TA, if set, or 0)\n"));
    }
  return (res);
}
