/* socks_wrfz */

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>
#include <syslog.h>
#include "socks.h"


int socks_wrfz(fc, confAddr, Nconf, useSyslog)
char *fc;
struct config *confAddr;
int Nconf;
int useSyslog;
{
	char *stringarea, *p;
	char *startaddr;
	int stringsize = 0;
	int i;
	struct config *cp;
	int fd;
	
	for (i = 0, cp = confAddr; i++ < Nconf; cp++) {
		if (cp->userlist != NULL)
			stringsize += strlen(cp->userlist) + 1;
		if (cp->serverlist != NULL)
			stringsize += strlen(cp->serverlist) + 1;
		if (cp->sdomain != NULL)
			stringsize += strlen(cp->sdomain) + 1;
		if (cp->ddomain != NULL)
			stringsize += strlen(cp->ddomain) + 1;
		if (cp->cmdp != NULL)
			stringsize += strlen(cp->cmdp) + 1;
	}

	if (stringsize != 0) {
		if ((stringarea = (char *)malloc(stringsize)) == NULL) {
			if (useSyslog)
				syslog(LOG_HIGH, "OUt of memory\n");
			else
				perror("socks_writefc(): malloc()");
			exit(1);
		}
		startaddr = stringarea - 1;
		p = stringarea;	
		for (i = 0, cp = confAddr; i++ < Nconf; cp++) {
			if (cp->userlist != NULL) {
				strcpy(p, cp->userlist);
				cp->userlist = (char *)(p - startaddr);
				p += strlen(p) + 1;
			}
			if (cp->serverlist != NULL) {
				strcpy(p, cp->serverlist);
				cp->serverlist = (char *)(p - startaddr);
				p += strlen(p) + 1;
			}
			if (cp->sdomain != NULL) {
				strcpy(p, cp->sdomain);
				cp->sdomain = (char *)(p - startaddr);
				p += strlen(p) + 1;
			}
			if (cp->ddomain != NULL) {
				strcpy(p, cp->ddomain);
				cp->ddomain = (char *)(p - startaddr);
				p += strlen(p) + 1;
			}
			if (cp->cmdp != NULL) {
				strcpy(p, cp->cmdp);
				cp->cmdp = (char *)(p - startaddr);
				p += strlen(p) + 1;
			}
		}
	}
	fd = creat(fc, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
	if (fd < 0) {
		if (useSyslog)
			syslog(LOG_HIGH, "Error: creat() %s: %m\n");
		else
			perror("socks_writefc(): creat()");
		exit(1);
	}
	if (write(fd, &Nconf, sizeof(Nconf)) != sizeof(Nconf)) {
		if (useSyslog)
			syslog(LOG_HIGH, "Error: write to %s: %m\n", fc);
		else
			perror("socks_writefc(): write()");
		exit(1);
	}
	if (write(fd, &stringsize, sizeof(stringsize)) != sizeof(stringsize)) {
		if (useSyslog)
			syslog(LOG_HIGH, "Error: write to %s: %m\n", fc);
		else
			perror("socks_writefc(): write()");
		exit(1);
	}
	if (write(fd, confAddr, Nconf * sizeof(struct config)) != (Nconf * sizeof(struct config))) {
		if (useSyslog)
			syslog(LOG_HIGH, "Error: write to %s: %m\n", fc);
		else
			perror("socks_writefc(): write()");
		exit(1);
	}
	if ((stringsize != 0) && (write(fd, stringarea, stringsize) != stringsize)) {
		if (useSyslog)
			syslog(LOG_HIGH, "Error: write to %s: %m\n", fc);
		else
			perror("socks_writefc(): write()");
		exit(1);
	}
	return 0;
}
