File: create_socket.c

package info (click to toggle)
i3-wm 4.25-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 7,676 kB
  • sloc: ansic: 30,144; perl: 19,136; sh: 70; makefile: 9
file content (81 lines) | stat: -rw-r--r-- 2,087 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*
 * vim:ts=4:sw=4:expandtab
 *
 * i3 - an improved tiling window manager
 * © 2009 Michael Stapelberg and contributors (see also: LICENSE)
 *
 */
#include "libi3.h"

#include <unistd.h>
#include <libgen.h>
#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>

/*
 * Creates the UNIX domain socket at the given path, sets it to non-blocking
 * mode, bind()s and listen()s on it.
 *
 * The full path to the socket is stored in the char* that out_socketpath points
 * to.
 *
 */
int create_socket(const char *filename, char **out_socketpath) {
    char *resolved = resolve_tilde(filename);
    DLOG("Creating UNIX socket at %s\n", resolved);
    char *copy = sstrdup(resolved);
    const char *dir = dirname(copy);
    if (!path_exists(dir)) {
        mkdirp(dir, DEFAULT_DIR_MODE);
    }
    free(copy);

    /* Check if the socket is in use by another process (this call does not
     * succeed if the socket is stale / the owner already exited) */
    int sockfd = ipc_connect_impl(resolved);
    if (sockfd != -1) {
        ELOG("Refusing to create UNIX socket at %s: Socket is already in use\n", resolved);
        close(sockfd);
        errno = EEXIST;
        return -1;
    }

    /* Unlink the unix domain socket before */
    unlink(resolved);

    sockfd = socket(AF_LOCAL, SOCK_STREAM, 0);
    if (sockfd < 0) {
        perror("socket()");
        free(resolved);
        return -1;
    }

    (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);

    struct sockaddr_un addr;
    memset(&addr, 0, sizeof(struct sockaddr_un));
    addr.sun_family = AF_LOCAL;
    strncpy(addr.sun_path, resolved, sizeof(addr.sun_path) - 1);
    if (bind(sockfd, (struct sockaddr *)&addr, sizeof(struct sockaddr_un)) < 0) {
        perror("bind()");
        free(resolved);
        return -1;
    }

    set_nonblock(sockfd);

    if (listen(sockfd, 5) < 0) {
        perror("listen()");
        free(resolved);
        return -1;
    }

    free(*out_socketpath);
    *out_socketpath = resolved;
    return sockfd;
}