/* rovm.c - ROVM Server ÀÇ main ÆÄÀÏ.
   Copyright (C) 2006 Weongyo Jeong (weongyo@gmail.com)

This file is part of ROVM.

ROVM 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, or (at your option) any later
version.

ROVM is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
for more details.

You should have received a copy of the GNU General Public License
along with GCC; see the file COPYING.  If not, write to the Free
Software Foundation, 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA.  */

#include <stdlib.h>

#include "types.h"
#include "mpool.h"
#include "tktree.h"
#include "clstree.h"
#include "sha1.h"
#include "listen.h"
#include "ssl_conf.h"
#include "rovm.h"

#include "thread.h"
#include "thread_mutex.h"
#include "thread_cond.h"

#include "mpm_worker_fdqueue.h"
#include "mpm_worker_pod.h"
#include "mpm_worker.h"

#include "connection.h"
#include "request.h"
#include "proc_rc.h"

#include "log.h"
#include "common.h"
#include "ticket.h"

#include "gc.h"
#include "utils.h"
#include "auth.h"

char *
rc_getword (rc_pool_t *atrans, const char **line, char stop)
{
  const char *pos = *line;
  int len;
  char *res;
  
  while ((*pos != stop) && *pos)
    ++pos;

  len = pos - *line;
  res = (char *) mp_alloc (atrans, len + 1);
  memcpy(res, *line, len);
  res[len] = 0;
  
  if (stop)
    {
      while (*pos == stop)
        ++pos;
    }
  *line = pos;
  
  return res;
}

authn_status 
check_password (request_rec *r, const char *user, const char *password)
{
  rc_configfile_t *f;
  char l[MAX_STRING_LEN];
  rc_status_t status;
  char *file_password = NULL;
  struct rovm *rovm = REQUEST_ROVM (r);
  
  status = rv_pcfg_openfile (&f, r->pool, CONF_PASSWORD_PATH (ROVM_CONF (rovm)));
  
  if (status != RC_SUCCESS) 
    {
      rovm_log (NULL, ROVMLOG_ERR, ROVMLOG_MARK,
                "Could not open password file: %s", CONF_PASSWORD_PATH (ROVM_CONF (rovm)));
      return AUTH_GENERAL_ERROR;
    }
  
  while (!(rc_cfg_getline (l, MAX_STRING_LEN, f))) 
    {
      const char *rpw, *w;
      
      /* Skip # or blank lines. */
      if ((l[0] == '#') || (!l[0])) 
        continue;
      
      rpw = l;
      w = rc_getword (r->pool, &rpw, ':');

      if (!strcmp(user, w)) 
        {
          file_password = rc_getword (r->pool, &rpw, ':');
          break;
        }
    }
  rc_cfg_closefile (f);
  
  if (!file_password)
    return AUTH_USER_NOT_FOUND;

  status = apr_password_validate (password, file_password);
  if (status != APR_SUCCESS)
    return AUTH_DENIED;

  return AUTH_GRANTED;
}
