/*-
 * Copyright (c) 2004 Free (Olivier Beyssac)
 * 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS 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 AUTHOR OR 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.
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <syslog.h>
#include <errno.h>
#include <ctype.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "client.h"


#define DEFAULT_HOST "localhost"
#define DEFAULT_PORT "2905"
#define BUF_SIZE (1024)


#define exit_error()                                                          \
 do {                                                                         \
   syslog(LOG_ERR, "Invalid options, usage: %s [-v] [host [port]]", argv[0]); \
   exit(EXIT_FAILURE);                                                        \
  } while (0)


/* Asks the BLD listening on host:port if ip is blacklisted */
extern char *bld_query(const char *host, const char *port, const char *ip)
{
  int sd, reply;
  static char *dunno = "dunno";
  static char *reject = "defer_if_permit Too many Users unknown from this IP";

  if ((sd = client_connect(host, port)) == -1)
    return dunno;
  else if ((reply = client_send_cmdi(sd, CMD_QUERY, ip)) == 421) {
    close(sd);
    return reject;
  }

  close(sd);

  return dunno;
}


int main(int argc, char **argv)
{
  FILE *in;
  struct in_addr inp;
  char *c, *basename, buf[BUF_SIZE];
  char *ip = NULL;
  char *host = DEFAULT_HOST;
  char *port = DEFAULT_PORT;
  int verbose = 0;
  
  if ((basename = strrchr(argv[0], '/')) != NULL)
    basename++;
  else
    basename = argv[0];
  
  openlog(basename, LOG_PID, LOG_MAIL);

  if (argc >= 2 && argc <= 4) {
    if (strcmp(argv[1], "-v") == 0) {
      verbose = 1;
      if (argc == 4) {
	host = argv[argc-2];
	port = argv[argc-1];
      } else if (argc == 3) {
	host = argv[argc-1];
      }
    } else {
      if (argc >= 2 && argc <= 3) {
	host = argv[1];
	if (argc == 3)
	  port = argv[2];
      } else
	exit_error();
    }
  } else if (argc != 1)
    exit_error();
  
  if ((in = fdopen(STDIN_FILENO, "r")) == NULL) {
    syslog(LOG_ERR, "Error while opening stdin: %s", strerror(errno));
    exit(EXIT_FAILURE);
  }
  
  while (fgets(buf, BUF_SIZE, in)) {
    if (!strncmp(buf, "client_address=", strlen("client_address=")) 
	&& (c = strchr(buf, '='))) {
      c++;
      c[strlen(c)-1] = '\0';
      ip = strdup(c);
    } else if (buf[0] == '\n') {
      char *action = "dunno";
      
      if (!ip || !inet_aton(ip, &inp))
	syslog(LOG_ERR, "invalid IP address: %s", ip);
      else
	action = bld_query(host, port, ip);
      
      printf("action=%s\n\n", action);
      fflush(stdout);
      if (verbose)
	syslog(LOG_INFO, "%s: %s", ip, action);
      
      if (ip) free(ip);
      break;
    }
  }
  
  fclose(in);
  
  exit(EXIT_SUCCESS);
}
