/* ====================================================================
 * Copyright (c) 1995 The Apache Group.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer. 
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. All advertising materials mentioning features or use of this
 *    software must display the following acknowledgment:
 *    "This product includes software developed by the Apache Group
 *    for use in the Apache HTTP server project (http://www.apache.org/)."
 *
 * 4. The names "Apache Server" and "Apache Group" must not be used to
 *    endorse or promote products derived from this software without
 *    prior written permission.
 *
 * 5. Redistributions of any form whatsoever must retain the following
 *    acknowledgment:
 *    "This product includes software developed by the Apache Group
 *    for use in the Apache HTTP server project (http://www.apache.org/)."
 *
 * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE APACHE GROUP OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Group and was originally based
 * on public domain software written at the National Center for
 * Supercomputing Applications, University of Illinois, Urbana-Champaign.
 * For more information on the Apache Group and the Apache HTTP server
 * project, please see <http://www.apache.org/>.
 *
 */


/*
 * http_auth: authentication
 * 
 * Rob McCool & Brian Behlendorf.
 * 
 * Adapted to Shambhala by rst.
 *
 * Adapted to NTB by Vinzenz F.  
 */

/* converted to use UNIX-System-Calls by Franz Vinzenz <vinzenz@ntb.ch>
 * 
 * This module uses the UNIX systemcalls getpwnam_r and getgrnam_r to 
 * retrieve the password and the groups for the user.
 * This allow the use of the system password database like NIS, 
 * NIS++, /etc/passwd, .. .
 *
 * Add The folowing Line to the Configuration - File:
 * Module sys_auth_module      mod_auth_sys.o
 *
 * There is also a special tag `valid-user` for the `require` configuration.
 * This allow acces for every authentificatet user. (It's like a special group
 * which includes all users on the system)
 *
 * 
 * Usage in per-directory access conf file:
 *
 *  AuthType Basic
 *  <Limit GET POST>
 *  require valid-user
 *  </Limit>
 *
 *  or
 *
 *  AuthType Basic
 *  <Limit GET>
 *  require user user1 user2 
 *  </Limit>

 *  AuthType Basic
 *  <Limit POST>
 *  require group group1 group2
 *  </Limit>

 * $Id: mod_auth_sys.c,v 1.4 1997/10/16 13:15:00 dougm Exp $
 */


#include "httpd.h"
#include "http_config.h"
#include "http_core.h"
#include "http_log.h"
#include "http_protocol.h"

typedef struct sys_auth_config_struct {
    int auth_authoritative;
} sys_auth_config_rec;

void *create_sys_auth_dir_config (pool *p, char *d)
{
    sys_auth_config_rec *sec =
    	(sys_auth_config_rec *) ap_pcalloc (p, sizeof(sys_auth_config_rec));
    sec->auth_authoritative = 1; /* keep the fortress secure by default */
    return sec;
}

command_rec sys_auth_cmds[] = {
  { "AuthAuthoritative", ap_set_flag_slot,
    (void*)XtOffsetOf(sys_auth_config_rec,auth_authoritative), 
      OR_AUTHCFG, FLAG, 
    "Set to 'Off' to allow access control to be passed along to lower modules if the UserID is not known to this module" },
  { NULL }
};

module MODULE_VAR_EXPORT sys_auth_module;

/* module sys_auth_module; */

#define BUFSIZE 512

/* Some Plattforms Do not have the reetrant functions 
 * getpwnam_r and getgrnam_r (eg. Linux)
 * So you should set the Constant: REENTRANT_FUNCTIONS to 0 
 */
#define REENTRANT_FUNCTIONS     0

/* On Some Plattforms the reetrant functions getpwnam_r and getgrnam_r 
 * returned 0 at OK (POSIX) 		=> 0, 
 * other returned NULL on FAILURE	=> 1
 * So you should set the Constant: RETURN_OK_VALUE to the approviate Value 
 */
#define RETURN_OK_VALUE		0

/* If you use Shadowed Password-Files you should set 
 * the Constant: SHADOW_PASSWORDS to 1 
 */
#define SHADOW_PASSWORDS     	1


/* ------------------------------------------------------------------------*/





#if SHADOW_PASSWORDS
#include <shadow.h>
#endif

char *get_sys_pw(char *user, char *buf) {

#if REENTRANT_FUNCTIONS
#if SHADOW_PASSWORDS
    struct spwd e1;
#if RETURN_OK_VALUE
    if (getspnam_r(user,&e1,buf,BUFSIZE)) 
#else
    if (!getspnam_r(user,&e1,buf,BUFSIZE)) 
#endif
        return e1.sp_pwdp;
#else
    struct passwd e1;
#if RETURN_OK_VALUE
    if (getpwnam_r(user,&e1,buf,BUFSIZE)) 
#else
#if !defined (__GLIBC__)
    if (!getpwnam_r(user,&e1,buf,BUFSIZE)) 
#else /* __GLIBC__ */
    struct passwd *e2;
    if (!getpwnam_r(user,&e1,buf,BUFSIZE,&e2))
#endif /* __GLIBC__ */
#endif
        return e1.pw_passwd;
#endif

#else
#if SHADOW_PASSWORDS
    struct spwd *e1;

    e1 = getspnam(user);
    if (e1) 
        return e1->sp_pwdp;
#else
    struct passwd *e1;

    e1 = getpwnam(user);
    if (e1) 
        return e1->pw_passwd;
#endif
#endif

    else
        return NULL;
}


char  ** get_sys_grp(const char *grp, char *buf) {

#if REENTRANT_FUNCTIONS

    struct group g1;

#if RETURN_OK_VALUE
    if (getgrnam_r(grp,&g1,buf,BUFSIZE)) 
#else
#if !defined (__GLIBC__)
    if (!getgrnam_r(grp,&g1,buf,BUFSIZE)) 
#else /* __GLIBC__ */
    struct group *g2;
    if (!getgrnam_r(grp,&g1,buf,BUFSIZE,&g2)) 
#endif /* __GLIBC__ */
#endif
        return g1.gr_mem;

#else
    char **grp_data;

    grp_data = getgrnam (grp)->gr_mem;

    if (grp_data[0]) 
        return grp_data;
#endif

    else
        return NULL;
}

int sys_authenticate_basic_user (request_rec *r) {
    sys_auth_config_rec *sec = (sys_auth_config_rec *)ap_get_module_config (r->per_dir_config, &sys_auth_module);
    conn_rec *c = r->connection;        
    char *sent_pw, *real_pw;
    char buf[BUFSIZE];
    int res;
    
    if ((res = ap_get_basic_auth_pw (r, &sent_pw)))
        return res;
    if(!(real_pw = get_sys_pw(c->user,buf))) {
	if (!(sec->auth_authoritative))
	    return DECLINED;
	ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r->server,
		    "user %s not found: %s", c->user, r->uri);
        ap_note_basic_auth_failure (r);
        return AUTH_REQUIRED;
    }    
    if(strcmp(real_pw,(char *)crypt(sent_pw,real_pw))) {
	ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r->server,
		    "user %s: password mismatch: %s", c->user, r->uri);
	ap_note_basic_auth_failure(r);
        return AUTH_REQUIRED;
    }
    return OK;
}
        
int sys_check_auth(request_rec *r) {
    sys_auth_config_rec *sec = (sys_auth_config_rec *)ap_get_module_config (r->per_dir_config, &sys_auth_module);
    char *user = r->connection->user;
    int m = r->method_number;
    char buf[BUFSIZE];
    
    array_header *reqs_arr = ap_requires (r);
    require_line *reqs = reqs_arr ? (require_line *)reqs_arr->elts : NULL;

    register int x;
    const char *t, *w;

    if (!reqs_arr) return DECLINED;
    
    for(x=0; x < reqs_arr->nelts; x++) {
      
        if (! (reqs[x].method_mask & (1 << m))) continue;
        
        t = reqs[x].requirement;
        w = ap_getword_conf(r->pool, &t);
        if(!strcmp(w,"group")) {
           char **mems;

           while(t[0]) {
               w = ap_getword_conf(r->pool, &t);
               if (!(mems = get_sys_grp(w,buf))) {
	           ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r->server,
		    "user %s not in Database: %s", user, r->uri);
                   ap_note_basic_auth_failure (r);
                   return AUTH_REQUIRED;
               }
               while (mems && *mems) {
                   if(!strcmp(*mems,user)) return OK; 
                   mems++;
               }
           }
	   ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r->server,
		    "user %s not in right group: %s", user, r->uri);
           ap_note_basic_auth_failure(r);
           return AUTH_REQUIRED;
       } else if(!strcmp(w,"user")) {
           while(t[0]) {
               w = ap_getword_conf(r->pool, &t);
               if(!strcmp(w,user)) return OK; 
           }
	   ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r->server,
		    "user %s: not authorized: %s", user, r->uri);
           ap_note_basic_auth_failure(r);
           return AUTH_REQUIRED;

       }
       else if(!strcmp(w,"valid-user")) return OK;
   }    
   return DECLINED;
}


module sys_auth_module = {
   STANDARD_MODULE_STUFF,
   NULL,                        /* initializer */
   create_sys_auth_dir_config,  /* dir config creater */
   NULL,                        /* dir merger --- default is to override */
   NULL,                        /* server config */
   NULL,                        /* merge server config */
   sys_auth_cmds,               /* command table */
   NULL,                        /* handlers */
   NULL,                        /* filename translation */
   sys_authenticate_basic_user, /* check_user_id */
   sys_check_auth,              /* check auth */
   NULL,                        /* check access */
   NULL,                        /* type_checker */
   NULL,                        /* fixups */
   NULL                         /* logger */
};
