]> git.ipfire.org Git - thirdparty/git.git/blob - unix-socket.c
unix-socket: eliminate static unix_stream_socket() helper function
[thirdparty/git.git] / unix-socket.c
1 #include "cache.h"
2 #include "unix-socket.h"
3
4 static int chdir_len(const char *orig, int len)
5 {
6 char *path = xmemdupz(orig, len);
7 int r = chdir(path);
8 free(path);
9 return r;
10 }
11
12 struct unix_sockaddr_context {
13 char *orig_dir;
14 };
15
16 static void unix_sockaddr_cleanup(struct unix_sockaddr_context *ctx)
17 {
18 if (!ctx->orig_dir)
19 return;
20 /*
21 * If we fail, we can't just return an error, since we have
22 * moved the cwd of the whole process, which could confuse calling
23 * code. We are better off to just die.
24 */
25 if (chdir(ctx->orig_dir) < 0)
26 die("unable to restore original working directory");
27 free(ctx->orig_dir);
28 }
29
30 static int unix_sockaddr_init(struct sockaddr_un *sa, const char *path,
31 struct unix_sockaddr_context *ctx)
32 {
33 int size = strlen(path) + 1;
34
35 ctx->orig_dir = NULL;
36 if (size > sizeof(sa->sun_path)) {
37 const char *slash = find_last_dir_sep(path);
38 const char *dir;
39 struct strbuf cwd = STRBUF_INIT;
40
41 if (!slash) {
42 errno = ENAMETOOLONG;
43 return -1;
44 }
45
46 dir = path;
47 path = slash + 1;
48 size = strlen(path) + 1;
49 if (size > sizeof(sa->sun_path)) {
50 errno = ENAMETOOLONG;
51 return -1;
52 }
53 if (strbuf_getcwd(&cwd))
54 return -1;
55 ctx->orig_dir = strbuf_detach(&cwd, NULL);
56 if (chdir_len(dir, slash - dir) < 0)
57 return -1;
58 }
59
60 memset(sa, 0, sizeof(*sa));
61 sa->sun_family = AF_UNIX;
62 memcpy(sa->sun_path, path, size);
63 return 0;
64 }
65
66 int unix_stream_connect(const char *path)
67 {
68 int fd = -1, saved_errno;
69 struct sockaddr_un sa;
70 struct unix_sockaddr_context ctx;
71
72 if (unix_sockaddr_init(&sa, path, &ctx) < 0)
73 return -1;
74 fd = socket(AF_UNIX, SOCK_STREAM, 0);
75 if (fd < 0)
76 goto fail;
77
78 if (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)
79 goto fail;
80 unix_sockaddr_cleanup(&ctx);
81 return fd;
82
83 fail:
84 saved_errno = errno;
85 if (fd != -1)
86 close(fd);
87 unix_sockaddr_cleanup(&ctx);
88 errno = saved_errno;
89 return -1;
90 }
91
92 int unix_stream_listen(const char *path)
93 {
94 int fd = -1, saved_errno;
95 struct sockaddr_un sa;
96 struct unix_sockaddr_context ctx;
97
98 unlink(path);
99
100 if (unix_sockaddr_init(&sa, path, &ctx) < 0)
101 return -1;
102 fd = socket(AF_UNIX, SOCK_STREAM, 0);
103 if (fd < 0)
104 goto fail;
105
106 if (bind(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)
107 goto fail;
108
109 if (listen(fd, 5) < 0)
110 goto fail;
111
112 unix_sockaddr_cleanup(&ctx);
113 return fd;
114
115 fail:
116 saved_errno = errno;
117 if (fd != -1)
118 close(fd);
119 unix_sockaddr_cleanup(&ctx);
120 errno = saved_errno;
121 return -1;
122 }