FIXME: hotpatch for compatibility with latest hg
[git] / unix-socket.c
1 #include "cache.h"
2 #include "unix-socket.h"
3
4 static 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
12 static 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
22 int 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
36 int 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         if (bind(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
45                 unlink(path);
46                 if (bind(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
47                         close(fd);
48                         return -1;
49                 }
50         }
51
52         if (listen(fd, 5) < 0) {
53                 close(fd);
54                 return -1;
55         }
56
57         return fd;
58 }