/*-*- Mode: C; c-basic-offset: 8 -*-*/
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ systemd 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; either version 2 of the License, or
+ (at your option) any later version.
+
+ systemd 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 systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
#include <assert.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <net/if.h>
+#include <sys/types.h>
+#include <sys/stat.h>
#include "macro.h"
#include "util.h"
memcpy(a->sockaddr.un.sun_path, s, l);
a->size = sizeof(sa_family_t) + l + 1;
- } else if (*s == '=') {
+ } else if (*s == '@') {
/* Abstract AF_UNIX socket */
size_t l;
} else {
if ((e = strchr(s, ':'))) {
- int r;
if ((r = safe_atou(e+1, &u)) < 0)
return r;
if (!(ret = new(char, sizeof(a->sockaddr.un.sun_path)+1)))
return -ENOMEM;
- ret[0] = '=';
+ ret[0] = '@';
memcpy(ret+1, a->sockaddr.un.sun_path+1, sizeof(a->sockaddr.un.sun_path)-1);
ret[sizeof(a->sockaddr.un.sun_path)] = 0;
}
}
-int socket_address_listen(const SocketAddress *a, int backlog, SocketAddressBindIPv6Only only, const char *bind_to_device, int *ret) {
+int socket_address_listen(
+ const SocketAddress *a,
+ int backlog,
+ SocketAddressBindIPv6Only only,
+ const char *bind_to_device,
+ mode_t directory_mode,
+ mode_t socket_mode,
+ int *ret) {
+
int r, fd, one;
assert(a);
assert(ret);
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) < 0)
goto fail;
- if (bind(fd, &a->sockaddr.sa, a->size) < 0)
+ if (socket_address_family(a) == AF_UNIX && a->sockaddr.un.sun_path[0] != 0) {
+ mode_t old_mask;
+
+ /* Create parents */
+ mkdir_parents(a->sockaddr.un.sun_path, directory_mode);
+
+ /* Enforce the right access mode for the socket*/
+ old_mask = umask(~ socket_mode);
+
+ /* Include the original umask in our mask */
+ umask(~socket_mode | old_mask);
+
+ r = bind(fd, &a->sockaddr.sa, a->size);
+
+ if (r < 0 && errno == EADDRINUSE) {
+ /* Unlink and try again */
+ unlink(a->sockaddr.un.sun_path);
+ r = bind(fd, &a->sockaddr.sa, a->size);
+ }
+
+ umask(old_mask);
+ } else
+ r = bind(fd, &a->sockaddr.sa, a->size);
+
+ if (r < 0)
goto fail;
if (a->type == SOCK_STREAM)