93 lines
2.9 KiB
C
93 lines
2.9 KiB
C
/***************************************************************************
|
|
* 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>
|
|
#include <unistd.h>
|
|
|
|
#include <fcntl.h>
|
|
#include <sys/types.h>
|
|
#include <sys/socket.h>
|
|
#include <sys/un.h>
|
|
#include <sys/stat.h>
|
|
|
|
#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;
|
|
}
|
|
|
|
if (fcntl(sockfd, F_SETFD, FD_CLOEXEC) < 0) {
|
|
log_print(LOG_WARN, "unix_listen(): fcntl(FD_CLOEXEC)");
|
|
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 (unlink(addr.sun_path) == -1) {
|
|
log_print(LOG_ERROR, "unix_listen: unlink()");
|
|
return -1;
|
|
}
|
|
|
|
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;
|
|
}
|