unix-socket-create.c revision d198989a7cac917ba0bd341a76d94e8a32267074
f46fce070a135ec6bb3078c104f32651ea84cdefTimo Sirainen/* Copyright (c) 2005-2008 Dovecot authors, see the included COPYING file */
f46fce070a135ec6bb3078c104f32651ea84cdefTimo Sirainen
f46fce070a135ec6bb3078c104f32651ea84cdefTimo Sirainen#include "lib.h"
f46fce070a135ec6bb3078c104f32651ea84cdefTimo Sirainen#include "network.h"
f46fce070a135ec6bb3078c104f32651ea84cdefTimo Sirainen#include "unix-socket-create.h"
f46fce070a135ec6bb3078c104f32651ea84cdefTimo Sirainen
f46fce070a135ec6bb3078c104f32651ea84cdefTimo Sirainen#include <unistd.h>
f46fce070a135ec6bb3078c104f32651ea84cdefTimo Sirainen#include <sys/stat.h>
f46fce070a135ec6bb3078c104f32651ea84cdefTimo Sirainen
539977f9257bd8985be5a8093658da266ae9cd19Timo Sirainenint unix_socket_create(const char *path, int mode,
f46fce070a135ec6bb3078c104f32651ea84cdefTimo Sirainen uid_t uid, gid_t gid, int backlog)
f46fce070a135ec6bb3078c104f32651ea84cdefTimo Sirainen{
f46fce070a135ec6bb3078c104f32651ea84cdefTimo Sirainen mode_t old_umask;
1382a978f06181d68151194ee4569378df16416aTimo Sirainen int fd;
311d3dd2078c1b711a0cef013ba43a94078c115cTimo Sirainen
f46fce070a135ec6bb3078c104f32651ea84cdefTimo Sirainen old_umask = umask(0777 ^ mode);
311d3dd2078c1b711a0cef013ba43a94078c115cTimo Sirainen fd = net_listen_unix_unlink_stale(path, backlog);
311d3dd2078c1b711a0cef013ba43a94078c115cTimo Sirainen umask(old_umask);
311d3dd2078c1b711a0cef013ba43a94078c115cTimo Sirainen
311d3dd2078c1b711a0cef013ba43a94078c115cTimo Sirainen if (fd < 0) {
311d3dd2078c1b711a0cef013ba43a94078c115cTimo Sirainen i_error("net_listen_unix(%s) failed: %m", path);
f46fce070a135ec6bb3078c104f32651ea84cdefTimo Sirainen return -1;
f46fce070a135ec6bb3078c104f32651ea84cdefTimo Sirainen }
f46fce070a135ec6bb3078c104f32651ea84cdefTimo Sirainen
0c1ed553b9add66a85e908b0c783c1b0dee1e0feTimo Sirainen if (uid != (uid_t)-1 || gid != (gid_t)-1) {
539977f9257bd8985be5a8093658da266ae9cd19Timo Sirainen /* set correct permissions */
f46fce070a135ec6bb3078c104f32651ea84cdefTimo Sirainen if (chown(path, uid, gid) < 0) {
f46fce070a135ec6bb3078c104f32651ea84cdefTimo Sirainen i_error("chown(%s, %s, %s) failed: %m",
f46fce070a135ec6bb3078c104f32651ea84cdefTimo Sirainen path, dec2str(uid), dec2str(gid));
f46fce070a135ec6bb3078c104f32651ea84cdefTimo Sirainen return -1;
f46fce070a135ec6bb3078c104f32651ea84cdefTimo Sirainen }
f46fce070a135ec6bb3078c104f32651ea84cdefTimo Sirainen }
f46fce070a135ec6bb3078c104f32651ea84cdefTimo Sirainen return fd;
e563b8a1457be8c08cc7567043c9f06b8243a025Timo Sirainen}
e563b8a1457be8c08cc7567043c9f06b8243a025Timo Sirainen
e563b8a1457be8c08cc7567043c9f06b8243a025Timo Sirainen