summaryrefslogtreecommitdiff
path: root/xs_unix_socket.h
blob: 5b642829a017cb442863e6f653fc3a01ae81443d (plain)
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
/* copyright (c) 2022 - 2024 grunfink et al. / MIT license */

#ifndef _XS_UNIX_SOCKET_H

#define _XS_UNIX_SOCKET_H

 int xs_unix_socket_server(const char *path, const char *grp);
 int xs_unix_socket_connect(const char *path);


#ifdef XS_IMPLEMENTATION

#include <sys/stat.h>
#include <sys/un.h>
#include <grp.h>

int xs_unix_socket_server(const char *path, const char *grp)
/* opens a unix-type server socket */
{
    int rs = -1;

    if ((rs = socket(AF_UNIX, SOCK_STREAM, 0)) != -1) {
        struct sockaddr_un sun = {0};
        mode_t mode = 0666;

        sun.sun_family = AF_UNIX;
        strncpy(sun.sun_path, path, sizeof(sun.sun_path));

        unlink(path);

        if (bind(rs, (struct sockaddr *)&sun, sizeof(sun)) == -1) {
            close(rs);
            return -1;
        }

        listen(rs, SOMAXCONN);

        if (grp != NULL) {
            struct group *g = NULL;

            /* if there is a group name, get its gid_t */
            g = getgrnam(grp);

            if (g != NULL && chown(path, -1, g->gr_gid) != -1)
                mode = 0660;
        }

        chmod(path, mode);
    }

    return rs;
}


int xs_unix_socket_connect(const char *path)
/* connects to a unix-type socket */
{
    int d = -1;

    if ((d = socket(AF_UNIX, SOCK_STREAM, 0)) != -1) {
        struct sockaddr_un sun = {0};

        sun.sun_family = AF_UNIX;
        strncpy(sun.sun_path, path, sizeof(sun.sun_path));

        if (connect(d, (struct sockaddr *)&sun, sizeof(sun)) == -1) {
            close(d);
            d = -1;
        }
    }

    return d;
}


#endif /* XS_IMPLEMENTATION */

#endif /* _XS_UNIX_SOCKET_H */