/* sockd_ckcf */

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <syslog.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <ctype.h>
#if (defined(sun) && !defined(SOLARIS)) || defined(sgi)
#include <strings.h>
#else
#include <string.h>
#endif
#include "socks.h"
#include "ident.h"

int sockd_ckcf(srcshp, dstshp, useIdentd, in, cfAddr, Ncf, no_identd_cmd, bad_id_cmd, useSyslog)
/* Return 0 if sockd should be used,
	  1 if direct connection should be made,
	 -1 if the connection request should be denied.
 */
struct sockshost_s *srcshp, *dstshp;
int useIdentd, in;
struct config *cfAddr;
int Ncf;
char *no_identd_cmd, *bad_id_cmd;
int useSyslog;
{
	unsigned short	dst_sin_port = ntohs(dstshp->port); 
	int i;
	struct config *cp;
	IDENT *ident_lookup(), *idp;
	int permit;
  
  
	for (i = 0, cp = cfAddr; i++ < Ncf; cp++) {

		if (socks_ckadr(srcshp, cp->sdomain, &cp->saddr, &cp->smask) &&
		    socks_ckadr(dstshp, cp->ddomain, &cp->daddr, &cp->dmask) &&
		    socks_ckusr(cp->userlist, srcshp->user, useSyslog) &&
		    socks_ckprt(cp->tst, dst_sin_port, cp->dport))
			goto GotIt;

	}

	return SOCKD_DENY;

GotIt:
	permit = cp->action;
	if (cp->use_identd == 3)
		useIdentd = 0;
	else if (cp->use_identd != 0)
		useIdentd = cp->use_identd;

	/* Don't bother to do identd unless we are to permit access */
	if ((useIdentd == 0) || (permit == SOCKD_DENY)) {
		if (cp->cmdp != NULL) {
			socks_shell_cmd(cp->cmdp, srcshp, dstshp);
		}
		return permit;
	}
	idp = ident_lookup(in, IDENTD_TIMEOUT);
	if (idp == NULL) {
		ident_free(idp);
		if (no_identd_cmd != NULL) {
			socks_shell_cmd(no_identd_cmd, srcshp, dstshp);
		}
		if ((useIdentd == 1) && (cp->cmdp != NULL)) {
		/* will permit access */
			socks_shell_cmd(cp->cmdp, srcshp, dstshp);
		}
		permit = -useIdentd;
		return permit;
	}
	strncpy(srcshp->ruser, idp->identifier, sizeof(srcshp->ruser));
	ident_free(idp);
	if (strcmp(srcshp->ruser, srcshp->user) != 0) {
		if (bad_id_cmd != NULL) {
			socks_shell_cmd(bad_id_cmd, srcshp, dstshp);
		}
		permit = -3;
		return permit;
	}
	if (cp->cmdp != NULL) {
		socks_shell_cmd(cp->cmdp, srcshp, dstshp);
	}
	return permit;
}

