##// END OF EJS Templates
chg: remove sockdirfd...
Jun Wu -
r30676:b83bddfc default
parent child Browse files
Show More
@@ -1,644 +1,638
1 /*
1 /*
2 * A fast client for Mercurial command server
2 * A fast client for Mercurial command server
3 *
3 *
4 * Copyright (c) 2011 Yuya Nishihara <yuya@tcha.org>
4 * Copyright (c) 2011 Yuya Nishihara <yuya@tcha.org>
5 *
5 *
6 * This software may be used and distributed according to the terms of the
6 * This software may be used and distributed according to the terms of the
7 * GNU General Public License version 2 or any later version.
7 * GNU General Public License version 2 or any later version.
8 */
8 */
9
9
10 #include <assert.h>
10 #include <assert.h>
11 #include <errno.h>
11 #include <errno.h>
12 #include <fcntl.h>
12 #include <fcntl.h>
13 #include <signal.h>
13 #include <signal.h>
14 #include <stdio.h>
14 #include <stdio.h>
15 #include <stdlib.h>
15 #include <stdlib.h>
16 #include <string.h>
16 #include <string.h>
17 #include <sys/file.h>
17 #include <sys/file.h>
18 #include <sys/stat.h>
18 #include <sys/stat.h>
19 #include <sys/types.h>
19 #include <sys/types.h>
20 #include <sys/un.h>
20 #include <sys/un.h>
21 #include <sys/wait.h>
21 #include <sys/wait.h>
22 #include <time.h>
22 #include <time.h>
23 #include <unistd.h>
23 #include <unistd.h>
24
24
25 #include "hgclient.h"
25 #include "hgclient.h"
26 #include "util.h"
26 #include "util.h"
27
27
28 #ifndef UNIX_PATH_MAX
28 #ifndef UNIX_PATH_MAX
29 #define UNIX_PATH_MAX (sizeof(((struct sockaddr_un *)NULL)->sun_path))
29 #define UNIX_PATH_MAX (sizeof(((struct sockaddr_un *)NULL)->sun_path))
30 #endif
30 #endif
31
31
32 struct cmdserveropts {
32 struct cmdserveropts {
33 char sockname[UNIX_PATH_MAX];
33 char sockname[UNIX_PATH_MAX];
34 char initsockname[UNIX_PATH_MAX];
34 char initsockname[UNIX_PATH_MAX];
35 char redirectsockname[UNIX_PATH_MAX];
35 char redirectsockname[UNIX_PATH_MAX];
36 size_t argsize;
36 size_t argsize;
37 const char **args;
37 const char **args;
38 int sockdirfd;
39 };
38 };
40
39
41 static void initcmdserveropts(struct cmdserveropts *opts) {
40 static void initcmdserveropts(struct cmdserveropts *opts) {
42 memset(opts, 0, sizeof(struct cmdserveropts));
41 memset(opts, 0, sizeof(struct cmdserveropts));
43 opts->sockdirfd = -1;
44 }
42 }
45
43
46 static void freecmdserveropts(struct cmdserveropts *opts) {
44 static void freecmdserveropts(struct cmdserveropts *opts) {
47 free(opts->args);
45 free(opts->args);
48 opts->args = NULL;
46 opts->args = NULL;
49 opts->argsize = 0;
47 opts->argsize = 0;
50 if (opts->sockdirfd >= 0) {
51 close(opts->sockdirfd);
52 opts->sockdirfd = -1;
53 }
54 }
48 }
55
49
56 /*
50 /*
57 * Test if an argument is a sensitive flag that should be passed to the server.
51 * Test if an argument is a sensitive flag that should be passed to the server.
58 * Return 0 if not, otherwise the number of arguments starting from the current
52 * Return 0 if not, otherwise the number of arguments starting from the current
59 * one that should be passed to the server.
53 * one that should be passed to the server.
60 */
54 */
61 static size_t testsensitiveflag(const char *arg)
55 static size_t testsensitiveflag(const char *arg)
62 {
56 {
63 static const struct {
57 static const struct {
64 const char *name;
58 const char *name;
65 size_t narg;
59 size_t narg;
66 } flags[] = {
60 } flags[] = {
67 {"--config", 1},
61 {"--config", 1},
68 {"--cwd", 1},
62 {"--cwd", 1},
69 {"--repo", 1},
63 {"--repo", 1},
70 {"--repository", 1},
64 {"--repository", 1},
71 {"--traceback", 0},
65 {"--traceback", 0},
72 {"-R", 1},
66 {"-R", 1},
73 };
67 };
74 size_t i;
68 size_t i;
75 for (i = 0; i < sizeof(flags) / sizeof(flags[0]); ++i) {
69 for (i = 0; i < sizeof(flags) / sizeof(flags[0]); ++i) {
76 size_t len = strlen(flags[i].name);
70 size_t len = strlen(flags[i].name);
77 size_t narg = flags[i].narg;
71 size_t narg = flags[i].narg;
78 if (memcmp(arg, flags[i].name, len) == 0) {
72 if (memcmp(arg, flags[i].name, len) == 0) {
79 if (arg[len] == '\0') {
73 if (arg[len] == '\0') {
80 /* --flag (value) */
74 /* --flag (value) */
81 return narg + 1;
75 return narg + 1;
82 } else if (arg[len] == '=' && narg > 0) {
76 } else if (arg[len] == '=' && narg > 0) {
83 /* --flag=value */
77 /* --flag=value */
84 return 1;
78 return 1;
85 } else if (flags[i].name[1] != '-') {
79 } else if (flags[i].name[1] != '-') {
86 /* short flag */
80 /* short flag */
87 return 1;
81 return 1;
88 }
82 }
89 }
83 }
90 }
84 }
91 return 0;
85 return 0;
92 }
86 }
93
87
94 /*
88 /*
95 * Parse argv[] and put sensitive flags to opts->args
89 * Parse argv[] and put sensitive flags to opts->args
96 */
90 */
97 static void setcmdserverargs(struct cmdserveropts *opts,
91 static void setcmdserverargs(struct cmdserveropts *opts,
98 int argc, const char *argv[])
92 int argc, const char *argv[])
99 {
93 {
100 size_t i, step;
94 size_t i, step;
101 opts->argsize = 0;
95 opts->argsize = 0;
102 for (i = 0, step = 1; i < (size_t)argc; i += step, step = 1) {
96 for (i = 0, step = 1; i < (size_t)argc; i += step, step = 1) {
103 if (!argv[i])
97 if (!argv[i])
104 continue; /* pass clang-analyse */
98 continue; /* pass clang-analyse */
105 if (strcmp(argv[i], "--") == 0)
99 if (strcmp(argv[i], "--") == 0)
106 break;
100 break;
107 size_t n = testsensitiveflag(argv[i]);
101 size_t n = testsensitiveflag(argv[i]);
108 if (n == 0 || i + n > (size_t)argc)
102 if (n == 0 || i + n > (size_t)argc)
109 continue;
103 continue;
110 opts->args = reallocx(opts->args,
104 opts->args = reallocx(opts->args,
111 (n + opts->argsize) * sizeof(char *));
105 (n + opts->argsize) * sizeof(char *));
112 memcpy(opts->args + opts->argsize, argv + i,
106 memcpy(opts->args + opts->argsize, argv + i,
113 sizeof(char *) * n);
107 sizeof(char *) * n);
114 opts->argsize += n;
108 opts->argsize += n;
115 step = n;
109 step = n;
116 }
110 }
117 }
111 }
118
112
119 static void preparesockdir(const char *sockdir)
113 static void preparesockdir(const char *sockdir)
120 {
114 {
121 int r;
115 int r;
122 r = mkdir(sockdir, 0700);
116 r = mkdir(sockdir, 0700);
123 if (r < 0 && errno != EEXIST)
117 if (r < 0 && errno != EEXIST)
124 abortmsgerrno("cannot create sockdir %s", sockdir);
118 abortmsgerrno("cannot create sockdir %s", sockdir);
125
119
126 struct stat st;
120 struct stat st;
127 r = lstat(sockdir, &st);
121 r = lstat(sockdir, &st);
128 if (r < 0)
122 if (r < 0)
129 abortmsgerrno("cannot stat %s", sockdir);
123 abortmsgerrno("cannot stat %s", sockdir);
130 if (!S_ISDIR(st.st_mode))
124 if (!S_ISDIR(st.st_mode))
131 abortmsg("cannot create sockdir %s (file exists)", sockdir);
125 abortmsg("cannot create sockdir %s (file exists)", sockdir);
132 if (st.st_uid != geteuid() || st.st_mode & 0077)
126 if (st.st_uid != geteuid() || st.st_mode & 0077)
133 abortmsg("insecure sockdir %s", sockdir);
127 abortmsg("insecure sockdir %s", sockdir);
134 }
128 }
135
129
136 static void setcmdserveropts(struct cmdserveropts *opts)
130 static void setcmdserveropts(struct cmdserveropts *opts)
137 {
131 {
138 int r;
132 int r;
139 char sockdir[UNIX_PATH_MAX];
133 char sockdir[UNIX_PATH_MAX];
140 const char *envsockname = getenv("CHGSOCKNAME");
134 const char *envsockname = getenv("CHGSOCKNAME");
141 if (!envsockname) {
135 if (!envsockname) {
142 /* by default, put socket file in secure directory
136 /* by default, put socket file in secure directory
143 * (permission of socket file may be ignored on some Unices) */
137 * (permission of socket file may be ignored on some Unices) */
144 const char *tmpdir = getenv("TMPDIR");
138 const char *tmpdir = getenv("TMPDIR");
145 if (!tmpdir)
139 if (!tmpdir)
146 tmpdir = "/tmp";
140 tmpdir = "/tmp";
147 r = snprintf(sockdir, sizeof(sockdir), "%s/chg%d",
141 r = snprintf(sockdir, sizeof(sockdir), "%s/chg%d",
148 tmpdir, geteuid());
142 tmpdir, geteuid());
149 if (r < 0 || (size_t)r >= sizeof(sockdir))
143 if (r < 0 || (size_t)r >= sizeof(sockdir))
150 abortmsg("too long TMPDIR (r = %d)", r);
144 abortmsg("too long TMPDIR (r = %d)", r);
151 preparesockdir(sockdir);
145 preparesockdir(sockdir);
152 }
146 }
153
147
154 const char *basename = (envsockname) ? envsockname : sockdir;
148 const char *basename = (envsockname) ? envsockname : sockdir;
155 const char *sockfmt = (envsockname) ? "%s" : "%s/server";
149 const char *sockfmt = (envsockname) ? "%s" : "%s/server";
156 r = snprintf(opts->sockname, sizeof(opts->sockname), sockfmt, basename);
150 r = snprintf(opts->sockname, sizeof(opts->sockname), sockfmt, basename);
157 if (r < 0 || (size_t)r >= sizeof(opts->sockname))
151 if (r < 0 || (size_t)r >= sizeof(opts->sockname))
158 abortmsg("too long TMPDIR or CHGSOCKNAME (r = %d)", r);
152 abortmsg("too long TMPDIR or CHGSOCKNAME (r = %d)", r);
159 r = snprintf(opts->initsockname, sizeof(opts->initsockname),
153 r = snprintf(opts->initsockname, sizeof(opts->initsockname),
160 "%s.%u", opts->sockname, (unsigned)getpid());
154 "%s.%u", opts->sockname, (unsigned)getpid());
161 if (r < 0 || (size_t)r >= sizeof(opts->initsockname))
155 if (r < 0 || (size_t)r >= sizeof(opts->initsockname))
162 abortmsg("too long TMPDIR or CHGSOCKNAME (r = %d)", r);
156 abortmsg("too long TMPDIR or CHGSOCKNAME (r = %d)", r);
163 }
157 }
164
158
165 static const char *gethgcmd(void)
159 static const char *gethgcmd(void)
166 {
160 {
167 static const char *hgcmd = NULL;
161 static const char *hgcmd = NULL;
168 if (!hgcmd) {
162 if (!hgcmd) {
169 hgcmd = getenv("CHGHG");
163 hgcmd = getenv("CHGHG");
170 if (!hgcmd || hgcmd[0] == '\0')
164 if (!hgcmd || hgcmd[0] == '\0')
171 hgcmd = getenv("HG");
165 hgcmd = getenv("HG");
172 if (!hgcmd || hgcmd[0] == '\0')
166 if (!hgcmd || hgcmd[0] == '\0')
173 #ifdef HGPATH
167 #ifdef HGPATH
174 hgcmd = (HGPATH);
168 hgcmd = (HGPATH);
175 #else
169 #else
176 hgcmd = "hg";
170 hgcmd = "hg";
177 #endif
171 #endif
178 }
172 }
179 return hgcmd;
173 return hgcmd;
180 }
174 }
181
175
182 static void execcmdserver(const struct cmdserveropts *opts)
176 static void execcmdserver(const struct cmdserveropts *opts)
183 {
177 {
184 const char *hgcmd = gethgcmd();
178 const char *hgcmd = gethgcmd();
185
179
186 const char *baseargv[] = {
180 const char *baseargv[] = {
187 hgcmd,
181 hgcmd,
188 "serve",
182 "serve",
189 "--cmdserver", "chgunix",
183 "--cmdserver", "chgunix",
190 "--address", opts->initsockname,
184 "--address", opts->initsockname,
191 "--daemon-postexec", "chdir:/",
185 "--daemon-postexec", "chdir:/",
192 };
186 };
193 size_t baseargvsize = sizeof(baseargv) / sizeof(baseargv[0]);
187 size_t baseargvsize = sizeof(baseargv) / sizeof(baseargv[0]);
194 size_t argsize = baseargvsize + opts->argsize + 1;
188 size_t argsize = baseargvsize + opts->argsize + 1;
195
189
196 const char **argv = mallocx(sizeof(char *) * argsize);
190 const char **argv = mallocx(sizeof(char *) * argsize);
197 memcpy(argv, baseargv, sizeof(baseargv));
191 memcpy(argv, baseargv, sizeof(baseargv));
198 memcpy(argv + baseargvsize, opts->args, sizeof(char *) * opts->argsize);
192 memcpy(argv + baseargvsize, opts->args, sizeof(char *) * opts->argsize);
199 argv[argsize - 1] = NULL;
193 argv[argsize - 1] = NULL;
200
194
201 if (putenv("CHGINTERNALMARK=") != 0)
195 if (putenv("CHGINTERNALMARK=") != 0)
202 abortmsgerrno("failed to putenv");
196 abortmsgerrno("failed to putenv");
203 if (execvp(hgcmd, (char **)argv) < 0)
197 if (execvp(hgcmd, (char **)argv) < 0)
204 abortmsgerrno("failed to exec cmdserver");
198 abortmsgerrno("failed to exec cmdserver");
205 free(argv);
199 free(argv);
206 }
200 }
207
201
208 /* Retry until we can connect to the server. Give up after some time. */
202 /* Retry until we can connect to the server. Give up after some time. */
209 static hgclient_t *retryconnectcmdserver(struct cmdserveropts *opts, pid_t pid)
203 static hgclient_t *retryconnectcmdserver(struct cmdserveropts *opts, pid_t pid)
210 {
204 {
211 static const struct timespec sleepreq = {0, 10 * 1000000};
205 static const struct timespec sleepreq = {0, 10 * 1000000};
212 int pst = 0;
206 int pst = 0;
213
207
214 debugmsg("try connect to %s repeatedly", opts->initsockname);
208 debugmsg("try connect to %s repeatedly", opts->initsockname);
215
209
216 unsigned int timeoutsec = 60; /* default: 60 seconds */
210 unsigned int timeoutsec = 60; /* default: 60 seconds */
217 const char *timeoutenv = getenv("CHGTIMEOUT");
211 const char *timeoutenv = getenv("CHGTIMEOUT");
218 if (timeoutenv)
212 if (timeoutenv)
219 sscanf(timeoutenv, "%u", &timeoutsec);
213 sscanf(timeoutenv, "%u", &timeoutsec);
220
214
221 for (unsigned int i = 0; !timeoutsec || i < timeoutsec * 100; i++) {
215 for (unsigned int i = 0; !timeoutsec || i < timeoutsec * 100; i++) {
222 hgclient_t *hgc = hgc_open(opts->initsockname);
216 hgclient_t *hgc = hgc_open(opts->initsockname);
223 if (hgc) {
217 if (hgc) {
224 debugmsg("rename %s to %s", opts->initsockname,
218 debugmsg("rename %s to %s", opts->initsockname,
225 opts->sockname);
219 opts->sockname);
226 int r = rename(opts->initsockname, opts->sockname);
220 int r = rename(opts->initsockname, opts->sockname);
227 if (r != 0)
221 if (r != 0)
228 abortmsgerrno("cannot rename");
222 abortmsgerrno("cannot rename");
229 return hgc;
223 return hgc;
230 }
224 }
231
225
232 if (pid > 0) {
226 if (pid > 0) {
233 /* collect zombie if child process fails to start */
227 /* collect zombie if child process fails to start */
234 int r = waitpid(pid, &pst, WNOHANG);
228 int r = waitpid(pid, &pst, WNOHANG);
235 if (r != 0)
229 if (r != 0)
236 goto cleanup;
230 goto cleanup;
237 }
231 }
238
232
239 nanosleep(&sleepreq, NULL);
233 nanosleep(&sleepreq, NULL);
240 }
234 }
241
235
242 abortmsg("timed out waiting for cmdserver %s", opts->initsockname);
236 abortmsg("timed out waiting for cmdserver %s", opts->initsockname);
243 return NULL;
237 return NULL;
244
238
245 cleanup:
239 cleanup:
246 if (WIFEXITED(pst)) {
240 if (WIFEXITED(pst)) {
247 if (WEXITSTATUS(pst) == 0)
241 if (WEXITSTATUS(pst) == 0)
248 abortmsg("could not connect to cmdserver "
242 abortmsg("could not connect to cmdserver "
249 "(exited with status 0)");
243 "(exited with status 0)");
250 debugmsg("cmdserver exited with status %d", WEXITSTATUS(pst));
244 debugmsg("cmdserver exited with status %d", WEXITSTATUS(pst));
251 exit(WEXITSTATUS(pst));
245 exit(WEXITSTATUS(pst));
252 } else if (WIFSIGNALED(pst)) {
246 } else if (WIFSIGNALED(pst)) {
253 abortmsg("cmdserver killed by signal %d", WTERMSIG(pst));
247 abortmsg("cmdserver killed by signal %d", WTERMSIG(pst));
254 } else {
248 } else {
255 abortmsg("error while waiting for cmdserver");
249 abortmsg("error while waiting for cmdserver");
256 }
250 }
257 return NULL;
251 return NULL;
258 }
252 }
259
253
260 /* Connect to a cmdserver. Will start a new server on demand. */
254 /* Connect to a cmdserver. Will start a new server on demand. */
261 static hgclient_t *connectcmdserver(struct cmdserveropts *opts)
255 static hgclient_t *connectcmdserver(struct cmdserveropts *opts)
262 {
256 {
263 const char *sockname = opts->redirectsockname[0] ?
257 const char *sockname = opts->redirectsockname[0] ?
264 opts->redirectsockname : opts->sockname;
258 opts->redirectsockname : opts->sockname;
265 debugmsg("try connect to %s", sockname);
259 debugmsg("try connect to %s", sockname);
266 hgclient_t *hgc = hgc_open(sockname);
260 hgclient_t *hgc = hgc_open(sockname);
267 if (hgc)
261 if (hgc)
268 return hgc;
262 return hgc;
269
263
270 /* prevent us from being connected to an outdated server: we were
264 /* prevent us from being connected to an outdated server: we were
271 * told by a server to redirect to opts->redirectsockname and that
265 * told by a server to redirect to opts->redirectsockname and that
272 * address does not work. we do not want to connect to the server
266 * address does not work. we do not want to connect to the server
273 * again because it will probably tell us the same thing. */
267 * again because it will probably tell us the same thing. */
274 if (sockname == opts->redirectsockname)
268 if (sockname == opts->redirectsockname)
275 unlink(opts->sockname);
269 unlink(opts->sockname);
276
270
277 debugmsg("start cmdserver at %s", opts->initsockname);
271 debugmsg("start cmdserver at %s", opts->initsockname);
278
272
279 pid_t pid = fork();
273 pid_t pid = fork();
280 if (pid < 0)
274 if (pid < 0)
281 abortmsg("failed to fork cmdserver process");
275 abortmsg("failed to fork cmdserver process");
282 if (pid == 0) {
276 if (pid == 0) {
283 execcmdserver(opts);
277 execcmdserver(opts);
284 } else {
278 } else {
285 hgc = retryconnectcmdserver(opts, pid);
279 hgc = retryconnectcmdserver(opts, pid);
286 }
280 }
287
281
288 return hgc;
282 return hgc;
289 }
283 }
290
284
291 static void killcmdserver(const struct cmdserveropts *opts)
285 static void killcmdserver(const struct cmdserveropts *opts)
292 {
286 {
293 /* resolve config hash */
287 /* resolve config hash */
294 char *resolvedpath = realpath(opts->sockname, NULL);
288 char *resolvedpath = realpath(opts->sockname, NULL);
295 if (resolvedpath) {
289 if (resolvedpath) {
296 unlink(resolvedpath);
290 unlink(resolvedpath);
297 free(resolvedpath);
291 free(resolvedpath);
298 }
292 }
299 }
293 }
300
294
301 static pid_t pagerpid = 0;
295 static pid_t pagerpid = 0;
302 static pid_t peerpgid = 0;
296 static pid_t peerpgid = 0;
303 static pid_t peerpid = 0;
297 static pid_t peerpid = 0;
304
298
305 static void forwardsignal(int sig)
299 static void forwardsignal(int sig)
306 {
300 {
307 assert(peerpid > 0);
301 assert(peerpid > 0);
308 if (kill(peerpid, sig) < 0)
302 if (kill(peerpid, sig) < 0)
309 abortmsgerrno("cannot kill %d", peerpid);
303 abortmsgerrno("cannot kill %d", peerpid);
310 debugmsg("forward signal %d", sig);
304 debugmsg("forward signal %d", sig);
311 }
305 }
312
306
313 static void forwardsignaltogroup(int sig)
307 static void forwardsignaltogroup(int sig)
314 {
308 {
315 /* prefer kill(-pgid, sig), fallback to pid if pgid is invalid */
309 /* prefer kill(-pgid, sig), fallback to pid if pgid is invalid */
316 pid_t killpid = peerpgid > 1 ? -peerpgid : peerpid;
310 pid_t killpid = peerpgid > 1 ? -peerpgid : peerpid;
317 if (kill(killpid, sig) < 0)
311 if (kill(killpid, sig) < 0)
318 abortmsgerrno("cannot kill %d", killpid);
312 abortmsgerrno("cannot kill %d", killpid);
319 debugmsg("forward signal %d to %d", sig, killpid);
313 debugmsg("forward signal %d to %d", sig, killpid);
320 }
314 }
321
315
322 static void handlestopsignal(int sig)
316 static void handlestopsignal(int sig)
323 {
317 {
324 sigset_t unblockset, oldset;
318 sigset_t unblockset, oldset;
325 struct sigaction sa, oldsa;
319 struct sigaction sa, oldsa;
326 if (sigemptyset(&unblockset) < 0)
320 if (sigemptyset(&unblockset) < 0)
327 goto error;
321 goto error;
328 if (sigaddset(&unblockset, sig) < 0)
322 if (sigaddset(&unblockset, sig) < 0)
329 goto error;
323 goto error;
330 memset(&sa, 0, sizeof(sa));
324 memset(&sa, 0, sizeof(sa));
331 sa.sa_handler = SIG_DFL;
325 sa.sa_handler = SIG_DFL;
332 sa.sa_flags = SA_RESTART;
326 sa.sa_flags = SA_RESTART;
333 if (sigemptyset(&sa.sa_mask) < 0)
327 if (sigemptyset(&sa.sa_mask) < 0)
334 goto error;
328 goto error;
335
329
336 forwardsignal(sig);
330 forwardsignal(sig);
337 if (raise(sig) < 0) /* resend to self */
331 if (raise(sig) < 0) /* resend to self */
338 goto error;
332 goto error;
339 if (sigaction(sig, &sa, &oldsa) < 0)
333 if (sigaction(sig, &sa, &oldsa) < 0)
340 goto error;
334 goto error;
341 if (sigprocmask(SIG_UNBLOCK, &unblockset, &oldset) < 0)
335 if (sigprocmask(SIG_UNBLOCK, &unblockset, &oldset) < 0)
342 goto error;
336 goto error;
343 /* resent signal will be handled before sigprocmask() returns */
337 /* resent signal will be handled before sigprocmask() returns */
344 if (sigprocmask(SIG_SETMASK, &oldset, NULL) < 0)
338 if (sigprocmask(SIG_SETMASK, &oldset, NULL) < 0)
345 goto error;
339 goto error;
346 if (sigaction(sig, &oldsa, NULL) < 0)
340 if (sigaction(sig, &oldsa, NULL) < 0)
347 goto error;
341 goto error;
348 return;
342 return;
349
343
350 error:
344 error:
351 abortmsgerrno("failed to handle stop signal");
345 abortmsgerrno("failed to handle stop signal");
352 }
346 }
353
347
354 static void handlechildsignal(int sig UNUSED_)
348 static void handlechildsignal(int sig UNUSED_)
355 {
349 {
356 if (peerpid == 0 || pagerpid == 0)
350 if (peerpid == 0 || pagerpid == 0)
357 return;
351 return;
358 /* if pager exits, notify the server with SIGPIPE immediately.
352 /* if pager exits, notify the server with SIGPIPE immediately.
359 * otherwise the server won't get SIGPIPE if it does not write
353 * otherwise the server won't get SIGPIPE if it does not write
360 * anything. (issue5278) */
354 * anything. (issue5278) */
361 if (waitpid(pagerpid, NULL, WNOHANG) == pagerpid)
355 if (waitpid(pagerpid, NULL, WNOHANG) == pagerpid)
362 kill(peerpid, SIGPIPE);
356 kill(peerpid, SIGPIPE);
363 }
357 }
364
358
365 static void setupsignalhandler(const hgclient_t *hgc)
359 static void setupsignalhandler(const hgclient_t *hgc)
366 {
360 {
367 pid_t pid = hgc_peerpid(hgc);
361 pid_t pid = hgc_peerpid(hgc);
368 if (pid <= 0)
362 if (pid <= 0)
369 return;
363 return;
370 peerpid = pid;
364 peerpid = pid;
371
365
372 pid_t pgid = hgc_peerpgid(hgc);
366 pid_t pgid = hgc_peerpgid(hgc);
373 peerpgid = (pgid <= 1 ? 0 : pgid);
367 peerpgid = (pgid <= 1 ? 0 : pgid);
374
368
375 struct sigaction sa;
369 struct sigaction sa;
376 memset(&sa, 0, sizeof(sa));
370 memset(&sa, 0, sizeof(sa));
377 sa.sa_handler = forwardsignaltogroup;
371 sa.sa_handler = forwardsignaltogroup;
378 sa.sa_flags = SA_RESTART;
372 sa.sa_flags = SA_RESTART;
379 if (sigemptyset(&sa.sa_mask) < 0)
373 if (sigemptyset(&sa.sa_mask) < 0)
380 goto error;
374 goto error;
381
375
382 if (sigaction(SIGHUP, &sa, NULL) < 0)
376 if (sigaction(SIGHUP, &sa, NULL) < 0)
383 goto error;
377 goto error;
384 if (sigaction(SIGINT, &sa, NULL) < 0)
378 if (sigaction(SIGINT, &sa, NULL) < 0)
385 goto error;
379 goto error;
386
380
387 /* terminate frontend by double SIGTERM in case of server freeze */
381 /* terminate frontend by double SIGTERM in case of server freeze */
388 sa.sa_handler = forwardsignal;
382 sa.sa_handler = forwardsignal;
389 sa.sa_flags |= SA_RESETHAND;
383 sa.sa_flags |= SA_RESETHAND;
390 if (sigaction(SIGTERM, &sa, NULL) < 0)
384 if (sigaction(SIGTERM, &sa, NULL) < 0)
391 goto error;
385 goto error;
392
386
393 /* notify the worker about window resize events */
387 /* notify the worker about window resize events */
394 sa.sa_flags = SA_RESTART;
388 sa.sa_flags = SA_RESTART;
395 if (sigaction(SIGWINCH, &sa, NULL) < 0)
389 if (sigaction(SIGWINCH, &sa, NULL) < 0)
396 goto error;
390 goto error;
397 /* propagate job control requests to worker */
391 /* propagate job control requests to worker */
398 sa.sa_handler = forwardsignal;
392 sa.sa_handler = forwardsignal;
399 sa.sa_flags = SA_RESTART;
393 sa.sa_flags = SA_RESTART;
400 if (sigaction(SIGCONT, &sa, NULL) < 0)
394 if (sigaction(SIGCONT, &sa, NULL) < 0)
401 goto error;
395 goto error;
402 sa.sa_handler = handlestopsignal;
396 sa.sa_handler = handlestopsignal;
403 sa.sa_flags = SA_RESTART;
397 sa.sa_flags = SA_RESTART;
404 if (sigaction(SIGTSTP, &sa, NULL) < 0)
398 if (sigaction(SIGTSTP, &sa, NULL) < 0)
405 goto error;
399 goto error;
406 /* get notified when pager exits */
400 /* get notified when pager exits */
407 sa.sa_handler = handlechildsignal;
401 sa.sa_handler = handlechildsignal;
408 sa.sa_flags = SA_RESTART;
402 sa.sa_flags = SA_RESTART;
409 if (sigaction(SIGCHLD, &sa, NULL) < 0)
403 if (sigaction(SIGCHLD, &sa, NULL) < 0)
410 goto error;
404 goto error;
411
405
412 return;
406 return;
413
407
414 error:
408 error:
415 abortmsgerrno("failed to set up signal handlers");
409 abortmsgerrno("failed to set up signal handlers");
416 }
410 }
417
411
418 static void restoresignalhandler()
412 static void restoresignalhandler()
419 {
413 {
420 struct sigaction sa;
414 struct sigaction sa;
421 memset(&sa, 0, sizeof(sa));
415 memset(&sa, 0, sizeof(sa));
422 sa.sa_handler = SIG_DFL;
416 sa.sa_handler = SIG_DFL;
423 sa.sa_flags = SA_RESTART;
417 sa.sa_flags = SA_RESTART;
424 if (sigemptyset(&sa.sa_mask) < 0)
418 if (sigemptyset(&sa.sa_mask) < 0)
425 goto error;
419 goto error;
426
420
427 if (sigaction(SIGHUP, &sa, NULL) < 0)
421 if (sigaction(SIGHUP, &sa, NULL) < 0)
428 goto error;
422 goto error;
429 if (sigaction(SIGTERM, &sa, NULL) < 0)
423 if (sigaction(SIGTERM, &sa, NULL) < 0)
430 goto error;
424 goto error;
431 if (sigaction(SIGWINCH, &sa, NULL) < 0)
425 if (sigaction(SIGWINCH, &sa, NULL) < 0)
432 goto error;
426 goto error;
433 if (sigaction(SIGCONT, &sa, NULL) < 0)
427 if (sigaction(SIGCONT, &sa, NULL) < 0)
434 goto error;
428 goto error;
435 if (sigaction(SIGTSTP, &sa, NULL) < 0)
429 if (sigaction(SIGTSTP, &sa, NULL) < 0)
436 goto error;
430 goto error;
437 if (sigaction(SIGCHLD, &sa, NULL) < 0)
431 if (sigaction(SIGCHLD, &sa, NULL) < 0)
438 goto error;
432 goto error;
439
433
440 /* ignore Ctrl+C while shutting down to make pager exits cleanly */
434 /* ignore Ctrl+C while shutting down to make pager exits cleanly */
441 sa.sa_handler = SIG_IGN;
435 sa.sa_handler = SIG_IGN;
442 if (sigaction(SIGINT, &sa, NULL) < 0)
436 if (sigaction(SIGINT, &sa, NULL) < 0)
443 goto error;
437 goto error;
444
438
445 peerpid = 0;
439 peerpid = 0;
446 return;
440 return;
447
441
448 error:
442 error:
449 abortmsgerrno("failed to restore signal handlers");
443 abortmsgerrno("failed to restore signal handlers");
450 }
444 }
451
445
452 /* This implementation is based on hgext/pager.py (post 369741ef7253)
446 /* This implementation is based on hgext/pager.py (post 369741ef7253)
453 * Return 0 if pager is not started, or pid of the pager */
447 * Return 0 if pager is not started, or pid of the pager */
454 static pid_t setuppager(hgclient_t *hgc, const char *const args[],
448 static pid_t setuppager(hgclient_t *hgc, const char *const args[],
455 size_t argsize)
449 size_t argsize)
456 {
450 {
457 const char *pagercmd = hgc_getpager(hgc, args, argsize);
451 const char *pagercmd = hgc_getpager(hgc, args, argsize);
458 if (!pagercmd)
452 if (!pagercmd)
459 return 0;
453 return 0;
460
454
461 int pipefds[2];
455 int pipefds[2];
462 if (pipe(pipefds) < 0)
456 if (pipe(pipefds) < 0)
463 return 0;
457 return 0;
464 pid_t pid = fork();
458 pid_t pid = fork();
465 if (pid < 0)
459 if (pid < 0)
466 goto error;
460 goto error;
467 if (pid > 0) {
461 if (pid > 0) {
468 close(pipefds[0]);
462 close(pipefds[0]);
469 if (dup2(pipefds[1], fileno(stdout)) < 0)
463 if (dup2(pipefds[1], fileno(stdout)) < 0)
470 goto error;
464 goto error;
471 if (isatty(fileno(stderr))) {
465 if (isatty(fileno(stderr))) {
472 if (dup2(pipefds[1], fileno(stderr)) < 0)
466 if (dup2(pipefds[1], fileno(stderr)) < 0)
473 goto error;
467 goto error;
474 }
468 }
475 close(pipefds[1]);
469 close(pipefds[1]);
476 hgc_attachio(hgc); /* reattach to pager */
470 hgc_attachio(hgc); /* reattach to pager */
477 return pid;
471 return pid;
478 } else {
472 } else {
479 dup2(pipefds[0], fileno(stdin));
473 dup2(pipefds[0], fileno(stdin));
480 close(pipefds[0]);
474 close(pipefds[0]);
481 close(pipefds[1]);
475 close(pipefds[1]);
482
476
483 int r = execlp("/bin/sh", "/bin/sh", "-c", pagercmd, NULL);
477 int r = execlp("/bin/sh", "/bin/sh", "-c", pagercmd, NULL);
484 if (r < 0) {
478 if (r < 0) {
485 abortmsgerrno("cannot start pager '%s'", pagercmd);
479 abortmsgerrno("cannot start pager '%s'", pagercmd);
486 }
480 }
487 return 0;
481 return 0;
488 }
482 }
489
483
490 error:
484 error:
491 close(pipefds[0]);
485 close(pipefds[0]);
492 close(pipefds[1]);
486 close(pipefds[1]);
493 abortmsgerrno("failed to prepare pager");
487 abortmsgerrno("failed to prepare pager");
494 return 0;
488 return 0;
495 }
489 }
496
490
497 static void waitpager(pid_t pid)
491 static void waitpager(pid_t pid)
498 {
492 {
499 /* close output streams to notify the pager its input ends */
493 /* close output streams to notify the pager its input ends */
500 fclose(stdout);
494 fclose(stdout);
501 fclose(stderr);
495 fclose(stderr);
502 while (1) {
496 while (1) {
503 pid_t ret = waitpid(pid, NULL, 0);
497 pid_t ret = waitpid(pid, NULL, 0);
504 if (ret == -1 && errno == EINTR)
498 if (ret == -1 && errno == EINTR)
505 continue;
499 continue;
506 break;
500 break;
507 }
501 }
508 }
502 }
509
503
510 /* Run instructions sent from the server like unlink and set redirect path
504 /* Run instructions sent from the server like unlink and set redirect path
511 * Return 1 if reconnect is needed, otherwise 0 */
505 * Return 1 if reconnect is needed, otherwise 0 */
512 static int runinstructions(struct cmdserveropts *opts, const char **insts)
506 static int runinstructions(struct cmdserveropts *opts, const char **insts)
513 {
507 {
514 int needreconnect = 0;
508 int needreconnect = 0;
515 if (!insts)
509 if (!insts)
516 return needreconnect;
510 return needreconnect;
517
511
518 assert(insts);
512 assert(insts);
519 opts->redirectsockname[0] = '\0';
513 opts->redirectsockname[0] = '\0';
520 const char **pinst;
514 const char **pinst;
521 for (pinst = insts; *pinst; pinst++) {
515 for (pinst = insts; *pinst; pinst++) {
522 debugmsg("instruction: %s", *pinst);
516 debugmsg("instruction: %s", *pinst);
523 if (strncmp(*pinst, "unlink ", 7) == 0) {
517 if (strncmp(*pinst, "unlink ", 7) == 0) {
524 unlink(*pinst + 7);
518 unlink(*pinst + 7);
525 } else if (strncmp(*pinst, "redirect ", 9) == 0) {
519 } else if (strncmp(*pinst, "redirect ", 9) == 0) {
526 int r = snprintf(opts->redirectsockname,
520 int r = snprintf(opts->redirectsockname,
527 sizeof(opts->redirectsockname),
521 sizeof(opts->redirectsockname),
528 "%s", *pinst + 9);
522 "%s", *pinst + 9);
529 if (r < 0 || r >= (int)sizeof(opts->redirectsockname))
523 if (r < 0 || r >= (int)sizeof(opts->redirectsockname))
530 abortmsg("redirect path is too long (%d)", r);
524 abortmsg("redirect path is too long (%d)", r);
531 needreconnect = 1;
525 needreconnect = 1;
532 } else if (strncmp(*pinst, "exit ", 5) == 0) {
526 } else if (strncmp(*pinst, "exit ", 5) == 0) {
533 int n = 0;
527 int n = 0;
534 if (sscanf(*pinst + 5, "%d", &n) != 1)
528 if (sscanf(*pinst + 5, "%d", &n) != 1)
535 abortmsg("cannot read the exit code");
529 abortmsg("cannot read the exit code");
536 exit(n);
530 exit(n);
537 } else if (strcmp(*pinst, "reconnect") == 0) {
531 } else if (strcmp(*pinst, "reconnect") == 0) {
538 needreconnect = 1;
532 needreconnect = 1;
539 } else {
533 } else {
540 abortmsg("unknown instruction: %s", *pinst);
534 abortmsg("unknown instruction: %s", *pinst);
541 }
535 }
542 }
536 }
543 return needreconnect;
537 return needreconnect;
544 }
538 }
545
539
546 /*
540 /*
547 * Test whether the command is unsupported or not. This is not designed to
541 * Test whether the command is unsupported or not. This is not designed to
548 * cover all cases. But it's fast, does not depend on the server and does
542 * cover all cases. But it's fast, does not depend on the server and does
549 * not return false positives.
543 * not return false positives.
550 */
544 */
551 static int isunsupported(int argc, const char *argv[])
545 static int isunsupported(int argc, const char *argv[])
552 {
546 {
553 enum {
547 enum {
554 SERVE = 1,
548 SERVE = 1,
555 DAEMON = 2,
549 DAEMON = 2,
556 SERVEDAEMON = SERVE | DAEMON,
550 SERVEDAEMON = SERVE | DAEMON,
557 TIME = 4,
551 TIME = 4,
558 };
552 };
559 unsigned int state = 0;
553 unsigned int state = 0;
560 int i;
554 int i;
561 for (i = 0; i < argc; ++i) {
555 for (i = 0; i < argc; ++i) {
562 if (strcmp(argv[i], "--") == 0)
556 if (strcmp(argv[i], "--") == 0)
563 break;
557 break;
564 if (i == 0 && strcmp("serve", argv[i]) == 0)
558 if (i == 0 && strcmp("serve", argv[i]) == 0)
565 state |= SERVE;
559 state |= SERVE;
566 else if (strcmp("-d", argv[i]) == 0 ||
560 else if (strcmp("-d", argv[i]) == 0 ||
567 strcmp("--daemon", argv[i]) == 0)
561 strcmp("--daemon", argv[i]) == 0)
568 state |= DAEMON;
562 state |= DAEMON;
569 else if (strcmp("--time", argv[i]) == 0)
563 else if (strcmp("--time", argv[i]) == 0)
570 state |= TIME;
564 state |= TIME;
571 }
565 }
572 return (state & TIME) == TIME ||
566 return (state & TIME) == TIME ||
573 (state & SERVEDAEMON) == SERVEDAEMON;
567 (state & SERVEDAEMON) == SERVEDAEMON;
574 }
568 }
575
569
576 static void execoriginalhg(const char *argv[])
570 static void execoriginalhg(const char *argv[])
577 {
571 {
578 debugmsg("execute original hg");
572 debugmsg("execute original hg");
579 if (execvp(gethgcmd(), (char **)argv) < 0)
573 if (execvp(gethgcmd(), (char **)argv) < 0)
580 abortmsgerrno("failed to exec original hg");
574 abortmsgerrno("failed to exec original hg");
581 }
575 }
582
576
583 int main(int argc, const char *argv[], const char *envp[])
577 int main(int argc, const char *argv[], const char *envp[])
584 {
578 {
585 if (getenv("CHGDEBUG"))
579 if (getenv("CHGDEBUG"))
586 enabledebugmsg();
580 enabledebugmsg();
587
581
588 if (!getenv("HGPLAIN") && isatty(fileno(stderr)))
582 if (!getenv("HGPLAIN") && isatty(fileno(stderr)))
589 enablecolor();
583 enablecolor();
590
584
591 if (getenv("CHGINTERNALMARK"))
585 if (getenv("CHGINTERNALMARK"))
592 abortmsg("chg started by chg detected.\n"
586 abortmsg("chg started by chg detected.\n"
593 "Please make sure ${HG:-hg} is not a symlink or "
587 "Please make sure ${HG:-hg} is not a symlink or "
594 "wrapper to chg. Alternatively, set $CHGHG to the "
588 "wrapper to chg. Alternatively, set $CHGHG to the "
595 "path of real hg.");
589 "path of real hg.");
596
590
597 if (isunsupported(argc - 1, argv + 1))
591 if (isunsupported(argc - 1, argv + 1))
598 execoriginalhg(argv);
592 execoriginalhg(argv);
599
593
600 struct cmdserveropts opts;
594 struct cmdserveropts opts;
601 initcmdserveropts(&opts);
595 initcmdserveropts(&opts);
602 setcmdserveropts(&opts);
596 setcmdserveropts(&opts);
603 setcmdserverargs(&opts, argc, argv);
597 setcmdserverargs(&opts, argc, argv);
604
598
605 if (argc == 2) {
599 if (argc == 2) {
606 if (strcmp(argv[1], "--kill-chg-daemon") == 0) {
600 if (strcmp(argv[1], "--kill-chg-daemon") == 0) {
607 killcmdserver(&opts);
601 killcmdserver(&opts);
608 return 0;
602 return 0;
609 }
603 }
610 }
604 }
611
605
612 hgclient_t *hgc;
606 hgclient_t *hgc;
613 size_t retry = 0;
607 size_t retry = 0;
614 while (1) {
608 while (1) {
615 hgc = connectcmdserver(&opts);
609 hgc = connectcmdserver(&opts);
616 if (!hgc)
610 if (!hgc)
617 abortmsg("cannot open hg client");
611 abortmsg("cannot open hg client");
618 hgc_setenv(hgc, envp);
612 hgc_setenv(hgc, envp);
619 const char **insts = hgc_validate(hgc, argv + 1, argc - 1);
613 const char **insts = hgc_validate(hgc, argv + 1, argc - 1);
620 int needreconnect = runinstructions(&opts, insts);
614 int needreconnect = runinstructions(&opts, insts);
621 free(insts);
615 free(insts);
622 if (!needreconnect)
616 if (!needreconnect)
623 break;
617 break;
624 hgc_close(hgc);
618 hgc_close(hgc);
625 if (++retry > 10)
619 if (++retry > 10)
626 abortmsg("too many redirections.\n"
620 abortmsg("too many redirections.\n"
627 "Please make sure %s is not a wrapper which "
621 "Please make sure %s is not a wrapper which "
628 "changes sensitive environment variables "
622 "changes sensitive environment variables "
629 "before executing hg. If you have to use a "
623 "before executing hg. If you have to use a "
630 "wrapper, wrap chg instead of hg.",
624 "wrapper, wrap chg instead of hg.",
631 gethgcmd());
625 gethgcmd());
632 }
626 }
633
627
634 setupsignalhandler(hgc);
628 setupsignalhandler(hgc);
635 pagerpid = setuppager(hgc, argv + 1, argc - 1);
629 pagerpid = setuppager(hgc, argv + 1, argc - 1);
636 int exitcode = hgc_runcommand(hgc, argv + 1, argc - 1);
630 int exitcode = hgc_runcommand(hgc, argv + 1, argc - 1);
637 restoresignalhandler();
631 restoresignalhandler();
638 hgc_close(hgc);
632 hgc_close(hgc);
639 freecmdserveropts(&opts);
633 freecmdserveropts(&opts);
640 if (pagerpid)
634 if (pagerpid)
641 waitpager(pagerpid);
635 waitpager(pagerpid);
642
636
643 return exitcode;
637 return exitcode;
644 }
638 }
General Comments 0
You need to be logged in to leave comments. Login now