/***** **** *** ** *  *   *    *     *       *     *   *  * ** *** **** *****\

    logresolve 2.0 - http://www.net/~tomr/progs/logresolve/

    logresolve.c - logresolve 2.0b3

    Tom Rathborne - tomr@uunet.ca - http://www.net/~tomr/

\***** **** *** ** *  *   *    *     *       *     *   *  * ** *** **** *****/

/*
 * System include files 
 */

#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <netdb.h>

/*
 * Logresolve include files 
 */

#include "logresolve.h"

#include "lr-nsrec.h"
#include "lr-stats.h"
#include "lr-ip.h"
#include "lr-hash.h"

#ifdef LR_DBM
#include "lr-dbm.h"
#endif

/*** FUNCTIONS BEGIN ********************************************************/

/*
 * getline - gets a line from stdin to s - at most maxlength chars
 */

int
getline(s, maxlength)
    char *s;
    int maxlength;
{
    char *cp;

    if (!fgets(s, maxlength, stdin))
	return (TRUE);
    if (cp = strchr(s, '\n'))
	*cp = '\0';
    return (FALSE);
}

/*
 * main - does it all!
 */

int
main(argc, argv)
    int argc;
    char *argv[];
{
    char *line, *chop;
    unsigned char ipnum[4];

    struct nsrec *record;
    struct nstab *table;

    FILE *lock;

#ifdef LR_DBM
    struct nsdbm *lrdbm;

    lrdbm = pdbm_open(LR_DBMNAME, LR_LOCKNAME, LR_READ);
#endif

    if (LR_NICE > 0) {
	setpriority(PRIO_PROCESS, getpid(), LR_NICE);
    }
    table = hash_new(LR_BUCKETS);
    line = (char *) malloc(MAXLINE);

    sethostent(TRUE);

    while (!getline(line, MAXLINE) && *line) {
	chop = line;

	while (*chop && *chop != ' ')
	    chop++;

	if (*chop) {
	    *chop = 0;
	    chop++;
	}
	if (str_ip(line, ipnum)) {
	    if (!(record = hash_lookup(table, ipnum))) {
#ifdef LR_DBM
		if (!(record = pdbm_lookup(lrdbm, ipnum)))
#endif
		{
		    record = ip_lookup(ipnum);
		}
		hash_insert(table, record);
	    }
	    if ((record->lookuptime < (time(NULL) - LR_EXPIRE))
/*
 * || (record->status == NO_RECOVERY) 
 */
		|| ((record->status == TRY_AGAIN)
		    && (record->tries < LR_TRIES))) {
		ip_relookup(record);
	    }
	    printf("%s %s\n", record->hostname, chop);

	} else {
	    printf("%s %s\n", line, chop);
	}
    }

    fflush(stdout);

    endhostent();

#ifdef LR_DBM
    pdbm_close(lrdbm);
    hash_dumpto_pdbm(table, LR_DBMNAME, LR_LOCKNAME);
#endif

    return (0);
}

/*** end of logresolve.c ***/
