syslog_in_unix.c
author viric@llimona
Thu, 06 Apr 2006 01:47:35 +0200
changeset 18 84fa30ea0b0d
parent 15 fea6e87812f0
child 26 7227789ca718
permissions -rw-r--r--
Ara sí - versió 1

#include <unistd.h> // Per les crides a fitxer
#include <stdio.h>  // Per l'I/O de stdin/stdout
#include <errno.h>  // Pels errors de les crides a fitxer
#include <string.h> // Per strerror()
#include <stdlib.h> // Per abort()
#include <sys/types.h>  // Per crides de fitxer
#include <sys/socket.h>  // Per les macros bool,true,false
#include <sys/un.h>  // Per les estructures dels unix sockets
#include <assert.h> // Per assert()

#include "rfc3164.h"

void show_help(const char * restrict program)
{
	printf("Usage: %s <unix_socket>\n", program);
}


int listen_unix(const char * restrict socketname)
{
	int socket_unix;
	struct sockaddr_un source_unix;
	int result;
	int sockopt;


	socket_unix = socket(PF_UNIX, SOCK_DGRAM, 0 );
	if (socket_unix == -1)
	{
		printf("Unix socket creation error: %s\n", strerror(errno));
		abort();
	}

	/* Allow socket reuse */
	sockopt = 1;
	result = setsockopt(socket_unix, SOL_SOCKET, SO_REUSEADDR, &sockopt,
		sizeof(sockopt));
	assert(result == 0);

	/* Unix socket listen address */
	memset(&source_unix, 0, sizeof(source_unix));
	source_unix.sun_family = AF_UNIX;
	strcpy(source_unix.sun_path, socketname);
	result = bind(socket_unix, (struct sockaddr *) &source_unix,
		sizeof(source_unix));
	assert(result == 0);

	/* Here we should take care of the socket permissions */

	return socket_unix;
}

void server_loop(const char * restrict socketname)
{
	int socket_unix;
	int result;
	char message[MESSAGE_LENGTH+1];


	socket_unix = listen_unix(socketname);

	result = 0;
	while ((result = recv(socket_unix, message, MESSAGE_LENGTH, 0)) >=0 )
	{
		process_message(message);
		/* Debug */
		if(!strcmp(message,"close"))
			break;
	}
	result = close(socket_unix);
	if (result == -1)
	{
		printf("Unix socket close error: %s\n", strerror(errno));
		abort();
	}
	result = unlink(socketname);
	if (result == -1)
	{
		printf("Unix socket unlink error: %s\n", strerror(errno));
		abort();
	}

}


int main(int argn, char **argv)
{
	/* Processem els paràmetres d'entrada */
	if (argn != 2) {
		show_help(argv[0]);
		return 2;
	}

	server_loop(argv[1]);

	return 0;
}