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

/*
 * Generic HTTP authentication, such as for use against a Google (tm) account
 *
 * See:
 *    http://code.google.com/apis/accounts/AuthForInstalledApps.html
 */

#ifndef lint
static const char copyright[] =
"Copyright (c) 2003-2011\n\
Distributed Systems Software.  All rights reserved.";
static const char revid[] =
  "$Id: local_http_auth.c 2528 2011-09-23 21:54:05Z brachman $";
#endif

#include "dacs.h"

static const char *log_module_name = "local_http_auth";

/*
 * Authenticate against a web-based authentication service.
 * Return 0 if authentication succeeds, -1 otherwise.
 *
 * Possible enhancement: optional regex that must match reply for
 * auth to succeed (or fail) in addition to the 200 status code.
 */
int
local_http_auth(char *username, char *password, char *aux, Url_auth *url_auth)
{
  int argnum, i, reply_len, status_code;
  char *cookies[2], *reply;
  Dsvec *dsv, *response_headers;
  Http_params *params;

  if (username == NULL || password == NULL || url_auth == NULL
	  || url_auth->url == NULL) {
	log_msg((LOG_ERROR_LEVEL, "Required argument is missing"));
	return(-1);
  }

  dsv = dsvec_init_size(NULL, sizeof(Http_params), 5);
  argnum = 0;
  params = http_param(dsv, NULL, username, NULL, 0);
  params->name = (url_auth->username_parameter != NULL)
	? url_auth->username_parameter : "USERNAME";
  params->filename = NULL;
  argnum++;

  params = http_param(dsv, NULL, password, NULL, 0);
  params->name = (url_auth->password_parameter != NULL)
	? url_auth->password_parameter : "PASSWORD";
  argnum++;

  for (i = 0; i < dsvec_len(url_auth->options); i++) {
	char *option;

	params = http_param(dsv, NULL, NULL, NULL, 0);
	option = dsvec_ptr(url_auth->options, i, char *);
	if (kwv_parse_str(option, &params->name, &params->value) == -1) {
	  log_msg((LOG_ERROR_LEVEL, "Invalid option: \"%s\"", option));
	  return(-1);
	}
	argnum++;
  }

  reply = NULL;
  reply_len = -1;
  cookies[0] = NULL;
  response_headers = dsvec_init(NULL, sizeof(char *));

  if (http_invoke(url_auth->url, url_auth->method,
				  ssl_verify ? HTTP_SSL_ON_VERIFY
				  : (use_ssl ? HTTP_SSL_ON : HTTP_SSL_URL_SCHEME),
				  argnum, (Http_params *) dsvec_base(dsv), NULL, cookies,
				  &reply, &reply_len, &status_code,
				  response_headers) == -1 || status_code != 200) {
	if (reply != NULL)
	  log_msg((LOG_ERROR_LEVEL, "%s", reply));
	return(-1);
  }

  return(0);
}

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

  emitted_dtd = 0;
  errmsg = "internal";
  username = password = aux = jurisdiction = NULL;

  dacs_init_allow_dups_default = 0;
  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);
	}
	if (errmsg != NULL)
	  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;
  }

  url_auth.method = HTTP_POST_METHOD;
  url_auth.url = NULL;
  url_auth.username_parameter = NULL;
  url_auth.password_parameter = NULL;
  url_auth.options = NULL;

  for (i = 0; i < kwv->nused; i++) {
	if (streq(kwv->pairs[i]->name, "USERNAME"))
	  username = kwv->pairs[i]->val;
	else if (streq(kwv->pairs[i]->name, "PASSWORD"))
	  password = kwv->pairs[i]->val;
	else if (streq(kwv->pairs[i]->name, "AUXILIARY"))
	  aux = kwv->pairs[i]->val;
	else if (streq(kwv->pairs[i]->name, "DACS_JURISDICTION"))
	  jurisdiction = kwv->pairs[i]->val;
	else if (streq(kwv->pairs[i]->name, "DACS_VERSION"))
	  ;
	else if (streq(kwv->pairs[i]->name, "AUTH_URL"))
	  url_auth.url = kwv->pairs[i]->val;
	else if (streq(kwv->pairs[i]->name, "AUTH_METHOD")) {
	  if ((url_auth.method = http_string_to_method(kwv->pairs[i]->val))
		  == HTTP_UNKNOWN_METHOD) {
		log_msg((LOG_ERROR_LEVEL, "Unrecognized AUTH_METHOD: \"%s\"",
				 kwv->pairs[i]->val));
		goto fail;
	  }
	}
	else if (streq(kwv->pairs[i]->name, "USERNAME_PARAMETER")
			 && url_auth.username_parameter == NULL)
	  url_auth.username_parameter = kwv->pairs[i]->val;
	else if (streq(kwv->pairs[i]->name, "PASSWORD_PARAMETER")
			 && url_auth.password_parameter == NULL)
	  url_auth.password_parameter = kwv->pairs[i]->val;
	else {
	  if (url_auth.options == NULL)
		url_auth.options = dsvec_init(NULL, sizeof(char *));

	  dsvec_add_ptr(url_auth.options,
					ds_xprintf("%s=%s", kwv->pairs[i]->name,
							   kwv->pairs[i]->val));
	}
  }

  if (url_auth.url == NULL) {
	errmsg = "Require AUTH_URL argument to be specified";
	goto fail;
  }

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

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

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

  /* XXX Map it? */
  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;
  printf("%s\n", make_xml_auth_reply_ok(&ok));

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