#include <mysql/mysql.h>
#include "control.h"
#include "mysql_queries.h"
#include "stralloc.h"

extern int connect_mysql();

extern MYSQL dbh, *mysql;
extern MYSQL_RES *result;

extern int do_query(stralloc *query, MYSQL_ROW *row);

/* qmail-smtpd needs to know if it can accept delivery for this domain */
int rcpthosts_mysql(char *addr, int len) {
  char *host;
  int i, at, num, rows;
  MYSQL_ROW row;
  stralloc real_host = { 0 };
  stralloc real_addr = { 0 };
  stralloc qmail_mysql_query = { 0 };

  /* maybe the client's so slow we lost the MySQL connection... */
  if (! connect_mysql()) return -1;

  num = len;
  host = addr + len;
  while (*host != '@') {
    host--;
    num--;
    if (host == addr) break;
  }
  at = num;

  /* no @ => envnoathost */
  if (num == 0) return 1;

  /* let's lose the @ we found and adjust len */
  host++;

  /* rest of this function adapted from Stephen Hawkins's patch */
  if (! stralloc_ready(&real_addr, 2 * (str_len(addr) - at) + 1)) return -1;
  mysql_escape_string(real_addr.s, addr, at);
  if (! stralloc_ready(&real_host, 2 * str_len(host) + 1)) return -1;
  mysql_escape_string(real_host.s, host, str_len(host));

#define ACK {\
  stralloc_free(&real_host);\
  stralloc_free(&real_addr);\
  return -1;\
}

#define OOF {\
  stralloc_free(&qmail_mysql_query);\
  ACK\
}

  if (! connect_mysql()) ACK

  len = real_host.len + str_len(RCPTHOSTS) + 2;
  if (! stralloc_ready(&qmail_mysql_query, len)) ACK
  if (! stralloc_cats(&qmail_mysql_query, RCPTHOSTS)) OOF
  if (! stralloc_cats(&qmail_mysql_query, real_host.s)) OOF
  if (! stralloc_cats(&qmail_mysql_query, "'")) OOF
  if (! stralloc_0(&qmail_mysql_query)) OOF

  rows = do_query(&qmail_mysql_query, &row);

  if (rows < 0) return -1;
  if (rows == 0) {
    stralloc_free(&real_host);
    stralloc_free(&real_addr);
    return -2;
  }

  len = real_addr.len + str_len(real_host.s) + str_len(VIRTUAL) + 2;
  if (! stralloc_ready(&qmail_mysql_query, len)) ACK
  if (! stralloc_cats(&qmail_mysql_query, VIRTUAL1)) OOF
  if (! stralloc_cats(&qmail_mysql_query, real_addr.s)) OOF
  if (! stralloc_cats(&qmail_mysql_query, VIRTUAL2)) OOF
  if (! stralloc_cats(&qmail_mysql_query, real_host.s)) OOF
  if (! stralloc_cats(&qmail_mysql_query, VIRTUAL3)) OOF
  if (! stralloc_0(&qmail_mysql_query)) OOF
  stralloc_free(&real_host);
  stralloc_free(&real_addr);

  rows = do_query(&qmail_mysql_query, &row);

  if (rows < 0) return -1;
  if (rows == 0) return -3;

  return 1;
}


syntax highlighted by Code2HTML, v. 0.9.1