1#include "cache.h"
2#include "unix-socket.h"
3
4static int unix_stream_socket(void)
5{
6 int fd = socket(AF_UNIX, SOCK_STREAM, 0);
7 if (fd < 0)
8 die_errno("unable to create socket");
9 return fd;
10}
11
12static void unix_sockaddr_init(struct sockaddr_un *sa, const char *path)
13{
14 int size = strlen(path) + 1;
15 if (size > sizeof(sa->sun_path))
16 die("socket path is too long to fit in sockaddr");
17 memset(sa, 0, sizeof(*sa));
18 sa->sun_family = AF_UNIX;
19 memcpy(sa->sun_path, path, size);
20}
21
22int unix_stream_connect(const char *path)
23{
24 int fd;
25 struct sockaddr_un sa;
26
27 unix_sockaddr_init(&sa, path);
28 fd = unix_stream_socket();
29 if (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
30 close(fd);
31 return -1;
32 }
33 return fd;
34}
35
36int unix_stream_listen(const char *path)
37{
38 int fd;
39 struct sockaddr_un sa;
40
41 unix_sockaddr_init(&sa, path);
42 fd = unix_stream_socket();
43
44 unlink(path);
45 if (bind(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
46 close(fd);
47 return -1;
48 }
49
50 if (listen(fd, 5) < 0) {
51 close(fd);
52 return -1;
53 }
54
55 return fd;
56}