bcb4e51a409d94ae670de96afb8483a4f7855294Stephan Bosch/* Copyright (c) 2005-2018 Dovecot authors, see the included COPYING file */
66bcc2a2f65576211f2f55edbe61130b96287fcdTimo Sirainen
66bcc2a2f65576211f2f55edbe61130b96287fcdTimo Sirainen#include "lib.h"
bdd36cfdba3ff66d25570a9ff568d69e1eb543cfTimo Sirainen#include "net.h"
66bcc2a2f65576211f2f55edbe61130b96287fcdTimo Sirainen#include "unix-socket-create.h"
66bcc2a2f65576211f2f55edbe61130b96287fcdTimo Sirainen
66bcc2a2f65576211f2f55edbe61130b96287fcdTimo Sirainen#include <unistd.h>
66bcc2a2f65576211f2f55edbe61130b96287fcdTimo Sirainen#include <sys/stat.h>
66bcc2a2f65576211f2f55edbe61130b96287fcdTimo Sirainen
66bcc2a2f65576211f2f55edbe61130b96287fcdTimo Sirainenint unix_socket_create(const char *path, int mode,
66bcc2a2f65576211f2f55edbe61130b96287fcdTimo Sirainen uid_t uid, gid_t gid, int backlog)
66bcc2a2f65576211f2f55edbe61130b96287fcdTimo Sirainen{
66bcc2a2f65576211f2f55edbe61130b96287fcdTimo Sirainen mode_t old_umask;
66bcc2a2f65576211f2f55edbe61130b96287fcdTimo Sirainen int fd;
66bcc2a2f65576211f2f55edbe61130b96287fcdTimo Sirainen
66bcc2a2f65576211f2f55edbe61130b96287fcdTimo Sirainen old_umask = umask(0777 ^ mode);
d198989a7cac917ba0bd341a76d94e8a32267074Timo Sirainen fd = net_listen_unix_unlink_stale(path, backlog);
66bcc2a2f65576211f2f55edbe61130b96287fcdTimo Sirainen umask(old_umask);
66bcc2a2f65576211f2f55edbe61130b96287fcdTimo Sirainen
66bcc2a2f65576211f2f55edbe61130b96287fcdTimo Sirainen if (fd < 0) {
66bcc2a2f65576211f2f55edbe61130b96287fcdTimo Sirainen i_error("net_listen_unix(%s) failed: %m", path);
66bcc2a2f65576211f2f55edbe61130b96287fcdTimo Sirainen return -1;
66bcc2a2f65576211f2f55edbe61130b96287fcdTimo Sirainen }
66bcc2a2f65576211f2f55edbe61130b96287fcdTimo Sirainen
66bcc2a2f65576211f2f55edbe61130b96287fcdTimo Sirainen if (uid != (uid_t)-1 || gid != (gid_t)-1) {
66bcc2a2f65576211f2f55edbe61130b96287fcdTimo Sirainen /* set correct permissions */
66bcc2a2f65576211f2f55edbe61130b96287fcdTimo Sirainen if (chown(path, uid, gid) < 0) {
66bcc2a2f65576211f2f55edbe61130b96287fcdTimo Sirainen i_error("chown(%s, %s, %s) failed: %m",
66bcc2a2f65576211f2f55edbe61130b96287fcdTimo Sirainen path, dec2str(uid), dec2str(gid));
af8b1248fed8529d26985460acdc4b1e4b7de675Timo Sirainen i_close_fd(&fd);
66bcc2a2f65576211f2f55edbe61130b96287fcdTimo Sirainen return -1;
66bcc2a2f65576211f2f55edbe61130b96287fcdTimo Sirainen }
66bcc2a2f65576211f2f55edbe61130b96287fcdTimo Sirainen }
66bcc2a2f65576211f2f55edbe61130b96287fcdTimo Sirainen return fd;
66bcc2a2f65576211f2f55edbe61130b96287fcdTimo Sirainen}
66bcc2a2f65576211f2f55edbe61130b96287fcdTimo Sirainen