alix-usv/daemon/unixsocket.c

96 lines
3.0 KiB
C
Raw Normal View History

2009-03-15 14:41:24 +01:00
/***************************************************************************
* Copyright (C) 07/2007 by Olaf Rempel *
* razzor@kopf-tisch.de *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; version 2 of the License *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include <string.h>
2009-04-19 14:24:06 +02:00
#include <unistd.h>
#include <fcntl.h>
2009-03-15 14:41:24 +01:00
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/stat.h>
2009-04-19 18:21:21 +02:00
#include <errno.h>
2009-03-15 14:41:24 +01:00
#include "logging.h"
int unix_listen(const char *filename)
{
int sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
if (sockfd == -1) {
log_print(LOG_ERROR, "unix_listen: socket()");
return -1;
}
2009-04-19 14:24:06 +02:00
if (fcntl(sockfd, F_SETFD, FD_CLOEXEC) < 0) {
log_print(LOG_WARN, "unix_listen(): fcntl(FD_CLOEXEC)");
return -1;
}
2009-03-15 14:41:24 +01:00
struct sockaddr_un addr;
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, filename, sizeof(addr.sun_path));
int len = sizeof(addr.sun_family) + strlen(addr.sun_path);
2009-04-19 18:21:21 +02:00
if (unlink(addr.sun_path) == -1 && errno != ENOENT) {
2009-04-19 14:24:06 +02:00
log_print(LOG_ERROR, "unix_listen: unlink()");
return -1;
}
2009-04-19 18:21:21 +02:00
errno = 0;
2009-03-15 14:41:24 +01:00
mode_t old_umask = umask(0077);
int ret = bind(sockfd, (struct sockaddr *) &addr, len);
umask(old_umask);
if (ret == -1) {
log_print(LOG_ERROR, "unix_listen: bind(%s)", filename);
close(sockfd);
return -1;
}
if (listen(sockfd, 5) == -1) {
log_print(LOG_ERROR, "unix_listen: listen()");
close(sockfd);
return -1;
}
return sockfd;
}
int unix_connect(const char *filename)
{
int sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
if (sockfd == -1) {
log_print(LOG_ERROR, "unix_connect: socket()");
return -1;
}
struct sockaddr_un addr;
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, filename, sizeof(addr.sun_path));
int len = sizeof(addr.sun_family) + strlen(addr.sun_path);
if (connect(sockfd, (struct sockaddr *)&addr, len) < 0) {
log_print(LOG_ERROR, "unix_connect: connect(%s)", filename);
close(sockfd);
return -1;
}
return sockfd;
}