/*
 * Copyright (c) 1996-2007, OpenFWTK Development Group
 * All rights reserved. See LICENSE.
 */

/* $Id: line.c,v 1.4 2007/09/10 02:49:13 arkenoi Exp $ */

#include <syslog.h>

#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <netinet/in.h>

#include "line.h"
#include "smftp.h"

#include "firewall.h"
#include "firewall2.h"
#include "fwfunc.h"
#include "auth.h"

ssize_t recvline(int i, char *line, int maxsize, int fl)
{
	char	*buffer = line;
	int	x;

	memset(buffer,0,maxsize);
	
	if (((x = (sogets(i, buffer, maxsize-1))) <= 0) ||
	    trim_eol(buffer)) {
		close(i);
		syslog(LOG_ERR,"error reading server data: %s", strerror(errno));
		sosay(0, "426 error reading server data");
		proxy_exit();
	} else {
		if (x >= maxsize-1) {
			buffer_overrun("recvline", NULL, maxsize); /* This function never returns */
		}
		return(x-=2);
	}
	return(-1);

}

void buffer_overrun(char *tag, char *buf, int limit)
{
	syslog(LOG_ERR,"securityalert: %s: buffer limit %d exceeded: %s", tag, limit, buf ? buf : "");
	send_msg(0,500, 0, "buffer limit exceeded");
	proxy_exit();
}

int trim_eol(s)
char	*s;
{
	if (!s || strcmp(s+strlen(s)-2,"\r\n"))
		return(1);
	else
		s[strlen(s)-2] = '\0';
	return(0);
}
