/*************************************************************************** * 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 #include #include #include #include #include #include #include #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 && errno != ENOENT) { log_print(LOG_ERROR, "unix_listen: unlink()"); return -1; } errno = 0; 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; }