/*
 * Copyright (c) 2003-2015
 * Distributed Systems Software.  All rights reserved.
 * See the file LICENSE for redistribution information.
 */

/*****************************************************************************
 * COPYRIGHT AND PERMISSION NOTICE
 * 
 * Copyright (c) 2001-2003 The Queen in Right of Canada
 * 
 * All rights reserved.
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation 
 * the rights to use, copy, modify, merge, publish, distribute, and/or sell
 * copies of the Software, and to permit persons to whom the Software is 
 * furnished to do so, provided that the above copyright notice(s) and this
 * permission notice appear in all copies of the Software and that both the
 * above copyright notice(s) and this permission notice appear in supporting
 * documentation.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.
 * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE 
 * BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES,
 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
 * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, 
 * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS 
 * SOFTWARE.
 * 
 * Except as contained in this notice, the name of a copyright holder shall not
 * be used in advertising or otherwise to promote the sale, use or other
 * dealings in this Software without prior written authorization of the
 * copyright holder.
 ***************************************************************************/

/*
 * DACS local authentication based on a private password file.
 * The password file is maintained by dacspasswd and must be run-time
 * accessible by this CGI program.
 */

#ifndef lint
static const char copyright[] =
"Copyright (c) 2003-2015\n\
Distributed Systems Software.  All rights reserved.";
static const char revid[] =
  "$Id: local_passwd_auth.c 2844 2015-08-24 22:50:16Z brachman $";
#endif

#include "dacs.h"

static const char *log_module_name = "local_passwd_authenticate";

/*
 * Simple password authentication
 * Return 0 if authentication succeeds, -1 otherwise.
 */
int
local_passwd_auth(char *username, char *given_passwd, char *aux)
{
  int st;
  const char *digest_name;
  Digest_desc *dd;
  Proc_lock *lock;
  Pw_entry *pw;
  Vfs_handle *h;

  if (username == NULL || given_passwd == NULL || given_passwd[0] == '\0')
	return(-1);

  if ((lock = proc_lock_create(PROC_LOCK_PASSWD)) == NULL) {
	log_msg((LOG_ERROR_LEVEL, "Cannot obtain lock"));
	return(-1);
  }

  if ((h = vfs_open_item_type("passwds")) == NULL) {
	log_msg((LOG_ALERT_LEVEL, "Can't open item type \"passwds\""));
	st = -1;
	goto done;
  }

  digest_name = NULL;
  if ((dd = passwd_get_digest_algorithm(digest_name)) == NULL) {
	log_msg((LOG_ERROR_LEVEL, "Can't get digest algorithm"));
	vfs_close(h);
	st = -1;
	goto done;
  }

  if ((pw = pw_read_entry(h, username)) == NULL) {
	log_msg((LOG_DEBUG_LEVEL, "Lookup of username '%s' failed", username));
	vfs_close(h);
	st = -1;
	goto done;
  }

  if (vfs_close(h) == -1)
	log_msg((LOG_ERROR_LEVEL, "vfs_close() failed"));

  st = -1;
  if (pw->state == PW_STATE_DISABLED)
	log_msg((LOG_NOTICE_LEVEL, "Account is disabled for username \"%s\"",
			 username));
  else if (passwd_check_digest(dd, given_passwd, pw) != 1) {
	log_msg((LOG_NOTICE_LEVEL,
			 "Password comparison failed for username \"%s\"", username));
  }
  else {
	log_msg((LOG_INFO_LEVEL, "Password comparison ok for username \"%s\"",
			 username));
	st = 0;
  }

 done:
  proc_lock_delete(lock);

  return(st);
}

#ifdef PROG
int
main(int argc, char **argv)
{
  int emitted_dtd;
  unsigned int ui;
  char *errmsg, *jurisdiction, *username, *password, *aux;
  Auth_reply_ok ok;
  Kwv *kwv;

  emitted_dtd = 0;
  errmsg = "Internal error";
  username = password = aux = jurisdiction = NULL;

  if (dacs_init(DACS_LOCAL_SERVICE, &argc, &argv, &kwv, &errmsg) == -1) {
	/* If we fail here, we may not have a DTD with which to reply... */
  fail:
	if (password != NULL)
	  strzap(password);
	if (aux != NULL)
	  strzap(aux);
	if (emitted_dtd) {
	  printf("%s\n", make_xml_auth_reply_failed(NULL, NULL));
	  emit_xml_trailer(stdout);
	}
	log_msg((LOG_ERROR_LEVEL, "Failed: reason=%s", errmsg));

	exit(1);
  }

  /* This must go after initialization. */
  emitted_dtd = emit_xml_header(stdout, "auth_reply");

  if (argc > 1) {
	errmsg = "Usage: unrecognized parameter";
	goto fail;
  }

  for (ui = 0; ui < kwv->nused; ui++) {
	if (streq(kwv->pairs[ui]->name, "USERNAME") && username == NULL)
	  username = kwv->pairs[ui]->val;
	else if (streq(kwv->pairs[ui]->name, "PASSWORD") && password == NULL)
	  password = kwv->pairs[ui]->val;
	else if (streq(kwv->pairs[ui]->name, "AUXILIARY") && aux == NULL)
	  aux = kwv->pairs[ui]->val;
	else if (streq(kwv->pairs[ui]->name, "DACS_JURISDICTION")
			 && jurisdiction == NULL)
	  jurisdiction = kwv->pairs[ui]->val;
	else if (streq(kwv->pairs[ui]->name, "DACS_VERSION"))
	  ;
	else
	  log_msg((LOG_DEBUG_LEVEL, "Parameter: '%s'", kwv->pairs[ui]->name));
  }

  /* Verify that we're truly responsible for DACS_JURISDICTION */
  if (dacs_verify_jurisdiction(jurisdiction) == -1) {
	log_msg((LOG_ERROR_LEVEL, "Missing or incorrect DACS_JURISDICTION"));
	goto fail;
  }

  if (local_passwd_auth(username, password, aux) == -1) {
	errmsg = "Username/Password incorrect";
	goto fail;
  }

  if (password != NULL)
	strzap(password);
  if (aux != NULL)
	strzap(aux);

  ok.username = username;
  /* If this wasn't specified, dacs_authenticate will use the default. */
  ok.lifetime = kwv_lookup_value(kwv, "CREDENTIALS_LIFETIME_SECS");
  ok.roles_reply = NULL;

#ifdef NOTDEF
  {
	/* Here's a simple demonstration of how roles might be returned. */
	Roles_reply *rr;

	rr = ALLOC(Roles_reply);
	rr->ok = ALLOC(Roles_reply_ok);
	rr->ok->roles = "auggie,harley,bandito";
	rr->failed = NULL;
	rr->error = NULL;
	ok.roles_reply = rr;
  }
#endif

  printf("%s\n", make_xml_auth_reply_ok(&ok));

  emit_xml_trailer(stdout);
  exit(0);
}
#endif
