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

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

#define MAXNUM 200

char * progname;

void use(void)
    {
        printf(gettext("%s (RSBAC %s)\n***\n"), progname, VERSION);
        printf(gettext("Use: %s [switches] TYPE add/remove target user1 user2...\n"), progname);
        printf(gettext("Use: %s [switches] TYPE get target\n"), progname);
        printf(gettext("     TYPE = PROCESS (add/remove only), DIR, FILE or FD (auto-select),\n"));
        printf(gettext("     target = pid or filename\n"));
        printf(gettext(" -h = this help, -- = no more flags,\n"));
        printf(gettext(" -z = do not also try numeric username as uid\n"));
        printf(gettext(" -m = set maximum number of returned members per file, default is %u\n"), MAXNUM);
        printf(gettext(" -t = set relative time-to-live for this cap entry in seconds (add only)\n"));
        printf(gettext(" -T = set absolute time-to-live for this cap entry in seconds (add only)\n"));
        printf(gettext(" -D = set relative time-to-live for this cap entry in days (add only)\n"));
        printf(gettext(" -V version = supply RSBAC integer version number for upgrading\n"));
        printf(gettext(" -N ta = transaction number (default = value of RSBAC_TA, if set, or 0)\n"));
    }

int main(int argc, char ** argv)
{
  int res = 0;
  rsbac_pid_t pid=0;
  rsbac_uid_t uid=RSBAC_NO_USER;
  enum rsbac_target_t target;
  rsbac_boolean_t remove = FALSE;
  int verbose = 0;
  rsbac_time_t ttl = RSBAC_LIST_TTL_KEEP;
  int maxnum = MAXNUM;
  rsbac_uid_t * userlist;
  rsbac_time_t * ttllist;
  int i;
  rsbac_list_ta_number_t ta_number = 0;
  u_int stopflags = FALSE;
  int nonumeric = 0;

  locale_init();

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

    if(env)
      ta_number = strtoul(env,0,0);
  }
  while((argc > 1) && (argv[1][0] == '-') && !stopflags)
    {
      char * pos = argv[1];
      pos++;
      while(*pos)
        {
          switch(*pos)
            {
              case '-':
                stopflags = TRUE;
                break;
              case 'h':
                use();
                return 0;
              case 'v':
                verbose++;
                break;
              case 'z':
                nonumeric=1;
                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 't':
                if(argc > 2)
                  {
                    ttl = strtoul(argv[2], 0, 10);
                    argc--;
                    argv++;
                  }
                else
                  fprintf(stderr, gettext("%s: missing ttl value for parameter %c\n"), progname, *pos);
                break;
              case 'D':
                if(argc > 2)
                  {
                    ttl = 86400 * strtoul(argv[2], 0, 10);
                    argc--;
                    argv++;
                  }
                else
                  fprintf(stderr, gettext("%s: missing ttl value for parameter %c\n"), progname, *pos);
                break;
              case 'T':
                if(argc > 2)
                  {
                    rsbac_time_t now = time(NULL);
                    ttl = strtoul(argv[2], 0, 10);
                    if(ttl > now)
                      {
                        ttl -= now;
                        argc--;
                        argv++;
                      }
                    else
                      {
                        fprintf(stderr,
                                gettext("%s: ttl value for parameter %c is in the past, exiting\n"), progname, *pos);
                        exit(1);
                      }
                  }
                else
                  fprintf(stderr, gettext("%s: missing ttl value for parameter %c\n"), progname, *pos);
                break;
              case 'V':
                if(argc < 3)
                  {
                    fprintf(stderr, gettext("%s: no version number for switch V\n"), progname);
                    exit(1);
                  }
                argv++;
                argc--;
                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 >= 5)
    {
        target = get_target_nr(argv[1]);
        if(   (target != T_PROCESS)
           && (target != T_FILE)
           && (target != T_DIR)
           && (target != T_FD)
          )
          {
            fprintf(stderr, gettext("%s: Invalid Target %s!\n"), progname, argv[1]);
            exit(1);
          }
        if(!strcmp(argv[2],"remove"))
          remove = TRUE;
        else
          if(strcmp(argv[2],"add"))
            {
              fprintf(stderr, gettext("%s: Invalid command %s!\n\n"), progname, argv[2]);
              exit(1);
            }
        if(target == T_PROCESS)
          pid=strtol(argv[3],0,10);
        for(i=4 ; i<argc; i++)
          {
            if(rsbac_get_uid(ta_number, &uid, argv[i], nonumeric))
              {
                fprintf(stderr, gettext("%s: Invalid User %s!\n"),
                        progname, argv[i]);
                continue;
              }
            if(target == T_PROCESS)
              {
                if(remove)
                  res = rsbac_mac_remove_p_tru(ta_number, pid, uid);
                else
                  res = rsbac_mac_add_p_tru(ta_number, pid, uid, ttl);
              }
            else
              {
                if(remove)
                  res = rsbac_mac_remove_f_tru(ta_number, argv[3], uid);
                else
                  res = rsbac_mac_add_f_tru(ta_number, argv[3], uid, ttl);
              }
            if(res < 0)
              error_exit(res);
          }
    }
  else
  if(argc == 4)
    {
        target = get_target_nr(argv[1]);
        if(   (target != T_FILE)
           && (target != T_DIR)
           && (target != T_FD)
           && (target != T_PROCESS)
          )
          {
            fprintf(stderr, gettext("%s: Invalid Target %s!\n"), progname, argv[1]);
            exit(1);
          }
        if(strcmp(argv[2],"get"))
          {
            fprintf(stderr, gettext("%s: Invalid command %s!\n\n"), progname, argv[2]);
            exit(1);
          }
        userlist = malloc(sizeof(*userlist) * maxnum);
        ttllist = malloc(sizeof(*ttllist) * maxnum);
        if(!userlist || !ttllist)
          error_exit(-ENOMEM);
        if(target == T_PROCESS)
          res = rsbac_mac_get_p_trulist(ta_number, strtoul(argv[3],0,0), userlist, ttllist, maxnum);
        else
          res = rsbac_mac_get_f_trulist(ta_number, argv[3], userlist, ttllist, maxnum);
        if(res < 0)
          {
            if(errno == RSBAC_ENOTFOUND)
              exit(0);
            else
              error_exit(res);
          }
        for(i=0; i<res; i++)
          if(ttllist[i])
            {
              if (RSBAC_UID_SET(userlist[i]))
                printf("%u/%u(ttl:%us) ", RSBAC_UID_SET(userlist[i]), RSBAC_UID_NUM(userlist[i]), ttllist[i]);
              else
                printf("%u(ttl:%us) ", RSBAC_UID_NUM(userlist[i]), ttllist[i]);
            }
          else
            {
              if (RSBAC_UID_SET(userlist[i]))
                printf("%u/%u ", RSBAC_UID_SET(userlist[i]), RSBAC_UID_NUM(userlist[i]));
              else
                printf("%u ", RSBAC_UID_NUM(userlist[i]));
            }
        printf("\n");
    }
  else
    {
      use();
      return 1;
    }
  exit(res);
}
