/*
   cipelib - library routines common to CIPE (user-mode part) and PKCIPE

   Copyright 2000 Olaf Titz <olaf@bigred.inka.de>

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License
   as published by the Free Software Foundation; either version
   2 of the License, or (at your option) any later version.
*/
/* $Id: secchk.c,v 1.1 2000/12/30 23:02:08 olaf Exp $ */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include "cipelib.h"

int secchk(const char *f, int fmask, int dmask, int v)
{
    struct stat s;
    char *b=strdup(f), *p;

    if (!b) {
        fprintf(stderr, "strdup error\n");
        return -1;
    }
#define err(f) do{ cipe_syslog(LOG_ERR, f, b); goto error; }while(0)

    if (b[0]!='/')
        err("%s: not absolute");
    if (stat(b, &s)<0) {
        if (v)
            cipe_syslog(LOG_ERR, "%s: stat: %m", b);
        goto error;
    }
    if (!S_ISREG(s.st_mode) || (s.st_mode&fmask) || (s.st_uid!=0))
        err("%s: incorrect permissions");
    while ((p=strrchr(b, '/'))) {
        if (p==b)
            p[1]='\0';
        else
            *p='\0';
        if (stat(b, &s)<0)
            err("%s: stat: %m");
        if (!S_ISDIR(s.st_mode) || (s.st_mode&dmask) || (s.st_uid!=0))
            err("%s: incorrect permissions");
        if (p==b)
            break;
    }
    free(b);
    return 0;

 error:
    free(b);
    return -1;
#undef err
}

