##// END OF EJS Templates
chg: close file descriptors when starting the daemon...
Mathias De Mare -
r46416:8711dc13 stable
parent child Browse files
Show More
@@ -1,517 +1,543 b''
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 <dirent.h>
11 #include <errno.h>
12 #include <errno.h>
12 #include <fcntl.h>
13 #include <fcntl.h>
13 #include <signal.h>
14 #include <signal.h>
14 #include <stdio.h>
15 #include <stdio.h>
15 #include <stdlib.h>
16 #include <stdlib.h>
16 #include <string.h>
17 #include <string.h>
17 #include <sys/file.h>
18 #include <sys/file.h>
18 #include <sys/stat.h>
19 #include <sys/stat.h>
19 #include <sys/types.h>
20 #include <sys/types.h>
20 #include <sys/un.h>
21 #include <sys/un.h>
21 #include <sys/wait.h>
22 #include <sys/wait.h>
22 #include <time.h>
23 #include <time.h>
23 #include <unistd.h>
24 #include <unistd.h>
24
25
25 #include "hgclient.h"
26 #include "hgclient.h"
26 #include "procutil.h"
27 #include "procutil.h"
27 #include "util.h"
28 #include "util.h"
28
29
29 #ifndef PATH_MAX
30 #ifndef PATH_MAX
30 #define PATH_MAX 4096
31 #define PATH_MAX 4096
31 #endif
32 #endif
32
33
33 struct cmdserveropts {
34 struct cmdserveropts {
34 char sockname[PATH_MAX];
35 char sockname[PATH_MAX];
35 char initsockname[PATH_MAX];
36 char initsockname[PATH_MAX];
36 char redirectsockname[PATH_MAX];
37 char redirectsockname[PATH_MAX];
37 size_t argsize;
38 size_t argsize;
38 const char **args;
39 const char **args;
39 };
40 };
40
41
41 static void initcmdserveropts(struct cmdserveropts *opts)
42 static void initcmdserveropts(struct cmdserveropts *opts)
42 {
43 {
43 memset(opts, 0, sizeof(struct cmdserveropts));
44 memset(opts, 0, sizeof(struct cmdserveropts));
44 }
45 }
45
46
46 static void freecmdserveropts(struct cmdserveropts *opts)
47 static void freecmdserveropts(struct cmdserveropts *opts)
47 {
48 {
48 free(opts->args);
49 free(opts->args);
49 opts->args = NULL;
50 opts->args = NULL;
50 opts->argsize = 0;
51 opts->argsize = 0;
51 }
52 }
52
53
53 /*
54 /*
54 * Test if an argument is a sensitive flag that should be passed to the server.
55 * Test if an argument is a sensitive flag that should be passed to the server.
55 * Return 0 if not, otherwise the number of arguments starting from the current
56 * Return 0 if not, otherwise the number of arguments starting from the current
56 * one that should be passed to the server.
57 * one that should be passed to the server.
57 */
58 */
58 static size_t testsensitiveflag(const char *arg)
59 static size_t testsensitiveflag(const char *arg)
59 {
60 {
60 static const struct {
61 static const struct {
61 const char *name;
62 const char *name;
62 size_t narg;
63 size_t narg;
63 } flags[] = {
64 } flags[] = {
64 {"--config", 1}, {"--cwd", 1}, {"--repo", 1},
65 {"--config", 1}, {"--cwd", 1}, {"--repo", 1},
65 {"--repository", 1}, {"--traceback", 0}, {"-R", 1},
66 {"--repository", 1}, {"--traceback", 0}, {"-R", 1},
66 };
67 };
67 size_t i;
68 size_t i;
68 for (i = 0; i < sizeof(flags) / sizeof(flags[0]); ++i) {
69 for (i = 0; i < sizeof(flags) / sizeof(flags[0]); ++i) {
69 size_t len = strlen(flags[i].name);
70 size_t len = strlen(flags[i].name);
70 size_t narg = flags[i].narg;
71 size_t narg = flags[i].narg;
71 if (memcmp(arg, flags[i].name, len) == 0) {
72 if (memcmp(arg, flags[i].name, len) == 0) {
72 if (arg[len] == '\0') {
73 if (arg[len] == '\0') {
73 /* --flag (value) */
74 /* --flag (value) */
74 return narg + 1;
75 return narg + 1;
75 } else if (arg[len] == '=' && narg > 0) {
76 } else if (arg[len] == '=' && narg > 0) {
76 /* --flag=value */
77 /* --flag=value */
77 return 1;
78 return 1;
78 } else if (flags[i].name[1] != '-') {
79 } else if (flags[i].name[1] != '-') {
79 /* short flag */
80 /* short flag */
80 return 1;
81 return 1;
81 }
82 }
82 }
83 }
83 }
84 }
84 return 0;
85 return 0;
85 }
86 }
86
87
87 /*
88 /*
88 * Parse argv[] and put sensitive flags to opts->args
89 * Parse argv[] and put sensitive flags to opts->args
89 */
90 */
90 static void setcmdserverargs(struct cmdserveropts *opts, int argc,
91 static void setcmdserverargs(struct cmdserveropts *opts, int argc,
91 const char *argv[])
92 const char *argv[])
92 {
93 {
93 size_t i, step;
94 size_t i, step;
94 opts->argsize = 0;
95 opts->argsize = 0;
95 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) {
96 if (!argv[i])
97 if (!argv[i])
97 continue; /* pass clang-analyse */
98 continue; /* pass clang-analyse */
98 if (strcmp(argv[i], "--") == 0)
99 if (strcmp(argv[i], "--") == 0)
99 break;
100 break;
100 size_t n = testsensitiveflag(argv[i]);
101 size_t n = testsensitiveflag(argv[i]);
101 if (n == 0 || i + n > (size_t)argc)
102 if (n == 0 || i + n > (size_t)argc)
102 continue;
103 continue;
103 opts->args =
104 opts->args =
104 reallocx(opts->args, (n + opts->argsize) * sizeof(char *));
105 reallocx(opts->args, (n + opts->argsize) * sizeof(char *));
105 memcpy(opts->args + opts->argsize, argv + i,
106 memcpy(opts->args + opts->argsize, argv + i,
106 sizeof(char *) * n);
107 sizeof(char *) * n);
107 opts->argsize += n;
108 opts->argsize += n;
108 step = n;
109 step = n;
109 }
110 }
110 }
111 }
111
112
112 static void preparesockdir(const char *sockdir)
113 static void preparesockdir(const char *sockdir)
113 {
114 {
114 int r;
115 int r;
115 r = mkdir(sockdir, 0700);
116 r = mkdir(sockdir, 0700);
116 if (r < 0 && errno != EEXIST)
117 if (r < 0 && errno != EEXIST)
117 abortmsgerrno("cannot create sockdir %s", sockdir);
118 abortmsgerrno("cannot create sockdir %s", sockdir);
118
119
119 struct stat st;
120 struct stat st;
120 r = lstat(sockdir, &st);
121 r = lstat(sockdir, &st);
121 if (r < 0)
122 if (r < 0)
122 abortmsgerrno("cannot stat %s", sockdir);
123 abortmsgerrno("cannot stat %s", sockdir);
123 if (!S_ISDIR(st.st_mode))
124 if (!S_ISDIR(st.st_mode))
124 abortmsg("cannot create sockdir %s (file exists)", sockdir);
125 abortmsg("cannot create sockdir %s (file exists)", sockdir);
125 if (st.st_uid != geteuid() || st.st_mode & 0077)
126 if (st.st_uid != geteuid() || st.st_mode & 0077)
126 abortmsg("insecure sockdir %s", sockdir);
127 abortmsg("insecure sockdir %s", sockdir);
127 }
128 }
128
129
129 /*
130 /*
130 * Check if a socket directory exists and is only owned by the current user.
131 * Check if a socket directory exists and is only owned by the current user.
131 * Return 1 if so, 0 if not. This is used to check if XDG_RUNTIME_DIR can be
132 * Return 1 if so, 0 if not. This is used to check if XDG_RUNTIME_DIR can be
132 * used or not. According to the specification [1], XDG_RUNTIME_DIR should be
133 * used or not. According to the specification [1], XDG_RUNTIME_DIR should be
133 * ignored if the directory is not owned by the user with mode 0700.
134 * ignored if the directory is not owned by the user with mode 0700.
134 * [1]: https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
135 * [1]: https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
135 */
136 */
136 static int checkruntimedir(const char *sockdir)
137 static int checkruntimedir(const char *sockdir)
137 {
138 {
138 struct stat st;
139 struct stat st;
139 int r = lstat(sockdir, &st);
140 int r = lstat(sockdir, &st);
140 if (r < 0) /* ex. does not exist */
141 if (r < 0) /* ex. does not exist */
141 return 0;
142 return 0;
142 if (!S_ISDIR(st.st_mode)) /* ex. is a file, not a directory */
143 if (!S_ISDIR(st.st_mode)) /* ex. is a file, not a directory */
143 return 0;
144 return 0;
144 return st.st_uid == geteuid() && (st.st_mode & 0777) == 0700;
145 return st.st_uid == geteuid() && (st.st_mode & 0777) == 0700;
145 }
146 }
146
147
147 static void getdefaultsockdir(char sockdir[], size_t size)
148 static void getdefaultsockdir(char sockdir[], size_t size)
148 {
149 {
149 /* by default, put socket file in secure directory
150 /* by default, put socket file in secure directory
150 * (${XDG_RUNTIME_DIR}/chg, or /${TMPDIR:-tmp}/chg$UID)
151 * (${XDG_RUNTIME_DIR}/chg, or /${TMPDIR:-tmp}/chg$UID)
151 * (permission of socket file may be ignored on some Unices) */
152 * (permission of socket file may be ignored on some Unices) */
152 const char *runtimedir = getenv("XDG_RUNTIME_DIR");
153 const char *runtimedir = getenv("XDG_RUNTIME_DIR");
153 int r;
154 int r;
154 if (runtimedir && checkruntimedir(runtimedir)) {
155 if (runtimedir && checkruntimedir(runtimedir)) {
155 r = snprintf(sockdir, size, "%s/chg", runtimedir);
156 r = snprintf(sockdir, size, "%s/chg", runtimedir);
156 } else {
157 } else {
157 const char *tmpdir = getenv("TMPDIR");
158 const char *tmpdir = getenv("TMPDIR");
158 if (!tmpdir)
159 if (!tmpdir)
159 tmpdir = "/tmp";
160 tmpdir = "/tmp";
160 r = snprintf(sockdir, size, "%s/chg%d", tmpdir, geteuid());
161 r = snprintf(sockdir, size, "%s/chg%d", tmpdir, geteuid());
161 }
162 }
162 if (r < 0 || (size_t)r >= size)
163 if (r < 0 || (size_t)r >= size)
163 abortmsg("too long TMPDIR (r = %d)", r);
164 abortmsg("too long TMPDIR (r = %d)", r);
164 }
165 }
165
166
166 static void setcmdserveropts(struct cmdserveropts *opts)
167 static void setcmdserveropts(struct cmdserveropts *opts)
167 {
168 {
168 int r;
169 int r;
169 char sockdir[PATH_MAX];
170 char sockdir[PATH_MAX];
170 const char *envsockname = getenv("CHGSOCKNAME");
171 const char *envsockname = getenv("CHGSOCKNAME");
171 if (!envsockname) {
172 if (!envsockname) {
172 getdefaultsockdir(sockdir, sizeof(sockdir));
173 getdefaultsockdir(sockdir, sizeof(sockdir));
173 preparesockdir(sockdir);
174 preparesockdir(sockdir);
174 }
175 }
175
176
176 const char *basename = (envsockname) ? envsockname : sockdir;
177 const char *basename = (envsockname) ? envsockname : sockdir;
177 const char *sockfmt = (envsockname) ? "%s" : "%s/server";
178 const char *sockfmt = (envsockname) ? "%s" : "%s/server";
178 r = snprintf(opts->sockname, sizeof(opts->sockname), sockfmt, basename);
179 r = snprintf(opts->sockname, sizeof(opts->sockname), sockfmt, basename);
179 if (r < 0 || (size_t)r >= sizeof(opts->sockname))
180 if (r < 0 || (size_t)r >= sizeof(opts->sockname))
180 abortmsg("too long TMPDIR or CHGSOCKNAME (r = %d)", r);
181 abortmsg("too long TMPDIR or CHGSOCKNAME (r = %d)", r);
181 r = snprintf(opts->initsockname, sizeof(opts->initsockname), "%s.%u",
182 r = snprintf(opts->initsockname, sizeof(opts->initsockname), "%s.%u",
182 opts->sockname, (unsigned)getpid());
183 opts->sockname, (unsigned)getpid());
183 if (r < 0 || (size_t)r >= sizeof(opts->initsockname))
184 if (r < 0 || (size_t)r >= sizeof(opts->initsockname))
184 abortmsg("too long TMPDIR or CHGSOCKNAME (r = %d)", r);
185 abortmsg("too long TMPDIR or CHGSOCKNAME (r = %d)", r);
185 }
186 }
186
187
187 /* If the current program is, say, /a/b/c/chg, returns /a/b/c/hg. */
188 /* If the current program is, say, /a/b/c/chg, returns /a/b/c/hg. */
188 static char *getrelhgcmd(void)
189 static char *getrelhgcmd(void)
189 {
190 {
190 ssize_t n;
191 ssize_t n;
191 char *res, *slash;
192 char *res, *slash;
192 int maxsize = 4096;
193 int maxsize = 4096;
193 res = malloc(maxsize);
194 res = malloc(maxsize);
194 if (res == NULL)
195 if (res == NULL)
195 goto cleanup;
196 goto cleanup;
196 n = readlink("/proc/self/exe", res, maxsize);
197 n = readlink("/proc/self/exe", res, maxsize);
197 if (n < 0 || n >= maxsize)
198 if (n < 0 || n >= maxsize)
198 goto cleanup;
199 goto cleanup;
199 res[n] = '\0';
200 res[n] = '\0';
200 slash = strrchr(res, '/');
201 slash = strrchr(res, '/');
201 if (slash == NULL)
202 if (slash == NULL)
202 goto cleanup;
203 goto cleanup;
203 /* 4 is strlen("/hg") + nul byte */
204 /* 4 is strlen("/hg") + nul byte */
204 if (slash + 4 >= res + maxsize)
205 if (slash + 4 >= res + maxsize)
205 goto cleanup;
206 goto cleanup;
206 memcpy(slash, "/hg", 4);
207 memcpy(slash, "/hg", 4);
207 return res;
208 return res;
208 cleanup:
209 cleanup:
209 free(res);
210 free(res);
210 return NULL;
211 return NULL;
211 }
212 }
212
213
213 static const char *gethgcmd(void)
214 static const char *gethgcmd(void)
214 {
215 {
215 static const char *hgcmd = NULL;
216 static const char *hgcmd = NULL;
216 #ifdef HGPATHREL
217 #ifdef HGPATHREL
217 int tryrelhgcmd = 1;
218 int tryrelhgcmd = 1;
218 #else
219 #else
219 int tryrelhgcmd = 0;
220 int tryrelhgcmd = 0;
220 #endif
221 #endif
221 if (!hgcmd) {
222 if (!hgcmd) {
222 hgcmd = getenv("CHGHG");
223 hgcmd = getenv("CHGHG");
223 if (!hgcmd || hgcmd[0] == '\0')
224 if (!hgcmd || hgcmd[0] == '\0')
224 hgcmd = getenv("HG");
225 hgcmd = getenv("HG");
225 if (tryrelhgcmd && (!hgcmd || hgcmd[0] == '\0'))
226 if (tryrelhgcmd && (!hgcmd || hgcmd[0] == '\0'))
226 hgcmd = getrelhgcmd();
227 hgcmd = getrelhgcmd();
227 if (!hgcmd || hgcmd[0] == '\0')
228 if (!hgcmd || hgcmd[0] == '\0')
228 #ifdef HGPATH
229 #ifdef HGPATH
229 hgcmd = (HGPATH);
230 hgcmd = (HGPATH);
230 #else
231 #else
231 hgcmd = "hg";
232 hgcmd = "hg";
232 #endif
233 #endif
233 }
234 }
234 return hgcmd;
235 return hgcmd;
235 }
236 }
236
237
237 static void execcmdserver(const struct cmdserveropts *opts)
238 static void execcmdserver(const struct cmdserveropts *opts)
238 {
239 {
239 const char *hgcmd = gethgcmd();
240 const char *hgcmd = gethgcmd();
240
241
241 const char *baseargv[] = {
242 const char *baseargv[] = {
242 hgcmd,
243 hgcmd,
243 "serve",
244 "serve",
244 "--cmdserver",
245 "--cmdserver",
245 "chgunix",
246 "chgunix",
246 "--address",
247 "--address",
247 opts->initsockname,
248 opts->initsockname,
248 "--daemon-postexec",
249 "--daemon-postexec",
249 "chdir:/",
250 "chdir:/",
250 };
251 };
251 size_t baseargvsize = sizeof(baseargv) / sizeof(baseargv[0]);
252 size_t baseargvsize = sizeof(baseargv) / sizeof(baseargv[0]);
252 size_t argsize = baseargvsize + opts->argsize + 1;
253 size_t argsize = baseargvsize + opts->argsize + 1;
253
254
254 const char **argv = mallocx(sizeof(char *) * argsize);
255 const char **argv = mallocx(sizeof(char *) * argsize);
255 memcpy(argv, baseargv, sizeof(baseargv));
256 memcpy(argv, baseargv, sizeof(baseargv));
256 if (opts->args) {
257 if (opts->args) {
257 size_t size = sizeof(char *) * opts->argsize;
258 size_t size = sizeof(char *) * opts->argsize;
258 memcpy(argv + baseargvsize, opts->args, size);
259 memcpy(argv + baseargvsize, opts->args, size);
259 }
260 }
260 argv[argsize - 1] = NULL;
261 argv[argsize - 1] = NULL;
261
262
262 const char *lc_ctype_env = getenv("LC_CTYPE");
263 const char *lc_ctype_env = getenv("LC_CTYPE");
263 if (lc_ctype_env == NULL) {
264 if (lc_ctype_env == NULL) {
264 if (putenv("CHG_CLEAR_LC_CTYPE=") != 0)
265 if (putenv("CHG_CLEAR_LC_CTYPE=") != 0)
265 abortmsgerrno("failed to putenv CHG_CLEAR_LC_CTYPE");
266 abortmsgerrno("failed to putenv CHG_CLEAR_LC_CTYPE");
266 } else {
267 } else {
267 if (setenv("CHGORIG_LC_CTYPE", lc_ctype_env, 1) != 0) {
268 if (setenv("CHGORIG_LC_CTYPE", lc_ctype_env, 1) != 0) {
268 abortmsgerrno("failed to setenv CHGORIG_LC_CTYPE");
269 abortmsgerrno("failed to setenv CHGORIG_LC_CTYPE");
269 }
270 }
270 }
271 }
271
272
273 /* close any open files to avoid hanging locks */
274 DIR *dp = opendir("/proc/self/fd");
275 if (dp != NULL) {
276 debugmsg("closing files based on /proc contents");
277 struct dirent *de;
278 while ((de = readdir(dp))) {
279 char *end;
280 long fd_value = strtol(de->d_name, &end, 10);
281 if (end == de->d_name) {
282 /* unable to convert to int (. or ..) */
283 continue;
284 }
285 if (errno == ERANGE) {
286 debugmsg("tried to parse %s, but range error occurred", de->d_name);
287 continue;
288 }
289 if (fd_value > STDERR_FILENO) {
290 int res = close(fd_value);
291 if (res) {
292 debugmsg("tried to close fd %ld: %d (errno: %d)", fd_value, res, errno);
293 }
294 }
295 }
296 }
297
272 if (putenv("CHGINTERNALMARK=") != 0)
298 if (putenv("CHGINTERNALMARK=") != 0)
273 abortmsgerrno("failed to putenv");
299 abortmsgerrno("failed to putenv");
274 if (execvp(hgcmd, (char **)argv) < 0)
300 if (execvp(hgcmd, (char **)argv) < 0)
275 abortmsgerrno("failed to exec cmdserver");
301 abortmsgerrno("failed to exec cmdserver");
276 free(argv);
302 free(argv);
277 }
303 }
278
304
279 /* Retry until we can connect to the server. Give up after some time. */
305 /* Retry until we can connect to the server. Give up after some time. */
280 static hgclient_t *retryconnectcmdserver(struct cmdserveropts *opts, pid_t pid)
306 static hgclient_t *retryconnectcmdserver(struct cmdserveropts *opts, pid_t pid)
281 {
307 {
282 static const struct timespec sleepreq = {0, 10 * 1000000};
308 static const struct timespec sleepreq = {0, 10 * 1000000};
283 int pst = 0;
309 int pst = 0;
284
310
285 debugmsg("try connect to %s repeatedly", opts->initsockname);
311 debugmsg("try connect to %s repeatedly", opts->initsockname);
286
312
287 unsigned int timeoutsec = 60; /* default: 60 seconds */
313 unsigned int timeoutsec = 60; /* default: 60 seconds */
288 const char *timeoutenv = getenv("CHGTIMEOUT");
314 const char *timeoutenv = getenv("CHGTIMEOUT");
289 if (timeoutenv)
315 if (timeoutenv)
290 sscanf(timeoutenv, "%u", &timeoutsec);
316 sscanf(timeoutenv, "%u", &timeoutsec);
291
317
292 for (unsigned int i = 0; !timeoutsec || i < timeoutsec * 100; i++) {
318 for (unsigned int i = 0; !timeoutsec || i < timeoutsec * 100; i++) {
293 hgclient_t *hgc = hgc_open(opts->initsockname);
319 hgclient_t *hgc = hgc_open(opts->initsockname);
294 if (hgc) {
320 if (hgc) {
295 debugmsg("rename %s to %s", opts->initsockname,
321 debugmsg("rename %s to %s", opts->initsockname,
296 opts->sockname);
322 opts->sockname);
297 int r = rename(opts->initsockname, opts->sockname);
323 int r = rename(opts->initsockname, opts->sockname);
298 if (r != 0)
324 if (r != 0)
299 abortmsgerrno("cannot rename");
325 abortmsgerrno("cannot rename");
300 return hgc;
326 return hgc;
301 }
327 }
302
328
303 if (pid > 0) {
329 if (pid > 0) {
304 /* collect zombie if child process fails to start */
330 /* collect zombie if child process fails to start */
305 int r = waitpid(pid, &pst, WNOHANG);
331 int r = waitpid(pid, &pst, WNOHANG);
306 if (r != 0)
332 if (r != 0)
307 goto cleanup;
333 goto cleanup;
308 }
334 }
309
335
310 nanosleep(&sleepreq, NULL);
336 nanosleep(&sleepreq, NULL);
311 }
337 }
312
338
313 abortmsg("timed out waiting for cmdserver %s", opts->initsockname);
339 abortmsg("timed out waiting for cmdserver %s", opts->initsockname);
314 return NULL;
340 return NULL;
315
341
316 cleanup:
342 cleanup:
317 if (WIFEXITED(pst)) {
343 if (WIFEXITED(pst)) {
318 if (WEXITSTATUS(pst) == 0)
344 if (WEXITSTATUS(pst) == 0)
319 abortmsg("could not connect to cmdserver "
345 abortmsg("could not connect to cmdserver "
320 "(exited with status 0)");
346 "(exited with status 0)");
321 debugmsg("cmdserver exited with status %d", WEXITSTATUS(pst));
347 debugmsg("cmdserver exited with status %d", WEXITSTATUS(pst));
322 exit(WEXITSTATUS(pst));
348 exit(WEXITSTATUS(pst));
323 } else if (WIFSIGNALED(pst)) {
349 } else if (WIFSIGNALED(pst)) {
324 abortmsg("cmdserver killed by signal %d", WTERMSIG(pst));
350 abortmsg("cmdserver killed by signal %d", WTERMSIG(pst));
325 } else {
351 } else {
326 abortmsg("error while waiting for cmdserver");
352 abortmsg("error while waiting for cmdserver");
327 }
353 }
328 return NULL;
354 return NULL;
329 }
355 }
330
356
331 /* Connect to a cmdserver. Will start a new server on demand. */
357 /* Connect to a cmdserver. Will start a new server on demand. */
332 static hgclient_t *connectcmdserver(struct cmdserveropts *opts)
358 static hgclient_t *connectcmdserver(struct cmdserveropts *opts)
333 {
359 {
334 const char *sockname =
360 const char *sockname =
335 opts->redirectsockname[0] ? opts->redirectsockname : opts->sockname;
361 opts->redirectsockname[0] ? opts->redirectsockname : opts->sockname;
336 debugmsg("try connect to %s", sockname);
362 debugmsg("try connect to %s", sockname);
337 hgclient_t *hgc = hgc_open(sockname);
363 hgclient_t *hgc = hgc_open(sockname);
338 if (hgc)
364 if (hgc)
339 return hgc;
365 return hgc;
340
366
341 /* prevent us from being connected to an outdated server: we were
367 /* prevent us from being connected to an outdated server: we were
342 * told by a server to redirect to opts->redirectsockname and that
368 * told by a server to redirect to opts->redirectsockname and that
343 * address does not work. we do not want to connect to the server
369 * address does not work. we do not want to connect to the server
344 * again because it will probably tell us the same thing. */
370 * again because it will probably tell us the same thing. */
345 if (sockname == opts->redirectsockname)
371 if (sockname == opts->redirectsockname)
346 unlink(opts->sockname);
372 unlink(opts->sockname);
347
373
348 debugmsg("start cmdserver at %s", opts->initsockname);
374 debugmsg("start cmdserver at %s", opts->initsockname);
349
375
350 pid_t pid = fork();
376 pid_t pid = fork();
351 if (pid < 0)
377 if (pid < 0)
352 abortmsg("failed to fork cmdserver process");
378 abortmsg("failed to fork cmdserver process");
353 if (pid == 0) {
379 if (pid == 0) {
354 execcmdserver(opts);
380 execcmdserver(opts);
355 } else {
381 } else {
356 hgc = retryconnectcmdserver(opts, pid);
382 hgc = retryconnectcmdserver(opts, pid);
357 }
383 }
358
384
359 return hgc;
385 return hgc;
360 }
386 }
361
387
362 static void killcmdserver(const struct cmdserveropts *opts)
388 static void killcmdserver(const struct cmdserveropts *opts)
363 {
389 {
364 /* resolve config hash */
390 /* resolve config hash */
365 char *resolvedpath = realpath(opts->sockname, NULL);
391 char *resolvedpath = realpath(opts->sockname, NULL);
366 if (resolvedpath) {
392 if (resolvedpath) {
367 unlink(resolvedpath);
393 unlink(resolvedpath);
368 free(resolvedpath);
394 free(resolvedpath);
369 }
395 }
370 }
396 }
371
397
372 /* Run instructions sent from the server like unlink and set redirect path
398 /* Run instructions sent from the server like unlink and set redirect path
373 * Return 1 if reconnect is needed, otherwise 0 */
399 * Return 1 if reconnect is needed, otherwise 0 */
374 static int runinstructions(struct cmdserveropts *opts, const char **insts)
400 static int runinstructions(struct cmdserveropts *opts, const char **insts)
375 {
401 {
376 int needreconnect = 0;
402 int needreconnect = 0;
377 if (!insts)
403 if (!insts)
378 return needreconnect;
404 return needreconnect;
379
405
380 assert(insts);
406 assert(insts);
381 opts->redirectsockname[0] = '\0';
407 opts->redirectsockname[0] = '\0';
382 const char **pinst;
408 const char **pinst;
383 for (pinst = insts; *pinst; pinst++) {
409 for (pinst = insts; *pinst; pinst++) {
384 debugmsg("instruction: %s", *pinst);
410 debugmsg("instruction: %s", *pinst);
385 if (strncmp(*pinst, "unlink ", 7) == 0) {
411 if (strncmp(*pinst, "unlink ", 7) == 0) {
386 unlink(*pinst + 7);
412 unlink(*pinst + 7);
387 } else if (strncmp(*pinst, "redirect ", 9) == 0) {
413 } else if (strncmp(*pinst, "redirect ", 9) == 0) {
388 int r = snprintf(opts->redirectsockname,
414 int r = snprintf(opts->redirectsockname,
389 sizeof(opts->redirectsockname), "%s",
415 sizeof(opts->redirectsockname), "%s",
390 *pinst + 9);
416 *pinst + 9);
391 if (r < 0 || r >= (int)sizeof(opts->redirectsockname))
417 if (r < 0 || r >= (int)sizeof(opts->redirectsockname))
392 abortmsg("redirect path is too long (%d)", r);
418 abortmsg("redirect path is too long (%d)", r);
393 needreconnect = 1;
419 needreconnect = 1;
394 } else if (strncmp(*pinst, "exit ", 5) == 0) {
420 } else if (strncmp(*pinst, "exit ", 5) == 0) {
395 int n = 0;
421 int n = 0;
396 if (sscanf(*pinst + 5, "%d", &n) != 1)
422 if (sscanf(*pinst + 5, "%d", &n) != 1)
397 abortmsg("cannot read the exit code");
423 abortmsg("cannot read the exit code");
398 exit(n);
424 exit(n);
399 } else if (strcmp(*pinst, "reconnect") == 0) {
425 } else if (strcmp(*pinst, "reconnect") == 0) {
400 needreconnect = 1;
426 needreconnect = 1;
401 } else {
427 } else {
402 abortmsg("unknown instruction: %s", *pinst);
428 abortmsg("unknown instruction: %s", *pinst);
403 }
429 }
404 }
430 }
405 return needreconnect;
431 return needreconnect;
406 }
432 }
407
433
408 /*
434 /*
409 * Test whether the command and the environment is unsupported or not.
435 * Test whether the command and the environment is unsupported or not.
410 *
436 *
411 * If any of the stdio file descriptors are not present (rare, but some tools
437 * If any of the stdio file descriptors are not present (rare, but some tools
412 * might spawn new processes without stdio instead of redirecting them to the
438 * might spawn new processes without stdio instead of redirecting them to the
413 * null device), then mark it as not supported because attachio won't work
439 * null device), then mark it as not supported because attachio won't work
414 * correctly.
440 * correctly.
415 *
441 *
416 * The command list is not designed to cover all cases. But it's fast, and does
442 * The command list is not designed to cover all cases. But it's fast, and does
417 * not depend on the server.
443 * not depend on the server.
418 */
444 */
419 static int isunsupported(int argc, const char *argv[])
445 static int isunsupported(int argc, const char *argv[])
420 {
446 {
421 enum { SERVE = 1,
447 enum { SERVE = 1,
422 DAEMON = 2,
448 DAEMON = 2,
423 SERVEDAEMON = SERVE | DAEMON,
449 SERVEDAEMON = SERVE | DAEMON,
424 };
450 };
425 unsigned int state = 0;
451 unsigned int state = 0;
426 int i;
452 int i;
427 /* use fcntl to test missing stdio fds */
453 /* use fcntl to test missing stdio fds */
428 if (fcntl(STDIN_FILENO, F_GETFD) == -1 ||
454 if (fcntl(STDIN_FILENO, F_GETFD) == -1 ||
429 fcntl(STDOUT_FILENO, F_GETFD) == -1 ||
455 fcntl(STDOUT_FILENO, F_GETFD) == -1 ||
430 fcntl(STDERR_FILENO, F_GETFD) == -1) {
456 fcntl(STDERR_FILENO, F_GETFD) == -1) {
431 debugmsg("stdio fds are missing");
457 debugmsg("stdio fds are missing");
432 return 1;
458 return 1;
433 }
459 }
434 for (i = 0; i < argc; ++i) {
460 for (i = 0; i < argc; ++i) {
435 if (strcmp(argv[i], "--") == 0)
461 if (strcmp(argv[i], "--") == 0)
436 break;
462 break;
437 /*
463 /*
438 * there can be false positives but no false negative
464 * there can be false positives but no false negative
439 * we cannot assume `serve` will always be first argument
465 * we cannot assume `serve` will always be first argument
440 * because global options can be passed before the command name
466 * because global options can be passed before the command name
441 */
467 */
442 if (strcmp("serve", argv[i]) == 0)
468 if (strcmp("serve", argv[i]) == 0)
443 state |= SERVE;
469 state |= SERVE;
444 else if (strcmp("-d", argv[i]) == 0 ||
470 else if (strcmp("-d", argv[i]) == 0 ||
445 strcmp("--daemon", argv[i]) == 0)
471 strcmp("--daemon", argv[i]) == 0)
446 state |= DAEMON;
472 state |= DAEMON;
447 }
473 }
448 return (state & SERVEDAEMON) == SERVEDAEMON;
474 return (state & SERVEDAEMON) == SERVEDAEMON;
449 }
475 }
450
476
451 static void execoriginalhg(const char *argv[])
477 static void execoriginalhg(const char *argv[])
452 {
478 {
453 debugmsg("execute original hg");
479 debugmsg("execute original hg");
454 if (execvp(gethgcmd(), (char **)argv) < 0)
480 if (execvp(gethgcmd(), (char **)argv) < 0)
455 abortmsgerrno("failed to exec original hg");
481 abortmsgerrno("failed to exec original hg");
456 }
482 }
457
483
458 int main(int argc, const char *argv[], const char *envp[])
484 int main(int argc, const char *argv[], const char *envp[])
459 {
485 {
460 if (getenv("CHGDEBUG"))
486 if (getenv("CHGDEBUG"))
461 enabledebugmsg();
487 enabledebugmsg();
462
488
463 if (!getenv("HGPLAIN") && isatty(fileno(stderr)))
489 if (!getenv("HGPLAIN") && isatty(fileno(stderr)))
464 enablecolor();
490 enablecolor();
465
491
466 if (getenv("CHGINTERNALMARK"))
492 if (getenv("CHGINTERNALMARK"))
467 abortmsg("chg started by chg detected.\n"
493 abortmsg("chg started by chg detected.\n"
468 "Please make sure ${HG:-hg} is not a symlink or "
494 "Please make sure ${HG:-hg} is not a symlink or "
469 "wrapper to chg. Alternatively, set $CHGHG to the "
495 "wrapper to chg. Alternatively, set $CHGHG to the "
470 "path of real hg.");
496 "path of real hg.");
471
497
472 if (isunsupported(argc - 1, argv + 1))
498 if (isunsupported(argc - 1, argv + 1))
473 execoriginalhg(argv);
499 execoriginalhg(argv);
474
500
475 struct cmdserveropts opts;
501 struct cmdserveropts opts;
476 initcmdserveropts(&opts);
502 initcmdserveropts(&opts);
477 setcmdserveropts(&opts);
503 setcmdserveropts(&opts);
478 setcmdserverargs(&opts, argc, argv);
504 setcmdserverargs(&opts, argc, argv);
479
505
480 if (argc == 2) {
506 if (argc == 2) {
481 if (strcmp(argv[1], "--kill-chg-daemon") == 0) {
507 if (strcmp(argv[1], "--kill-chg-daemon") == 0) {
482 killcmdserver(&opts);
508 killcmdserver(&opts);
483 return 0;
509 return 0;
484 }
510 }
485 }
511 }
486
512
487 hgclient_t *hgc;
513 hgclient_t *hgc;
488 size_t retry = 0;
514 size_t retry = 0;
489 while (1) {
515 while (1) {
490 hgc = connectcmdserver(&opts);
516 hgc = connectcmdserver(&opts);
491 if (!hgc)
517 if (!hgc)
492 abortmsg("cannot open hg client");
518 abortmsg("cannot open hg client");
493 hgc_setenv(hgc, envp);
519 hgc_setenv(hgc, envp);
494 const char **insts = hgc_validate(hgc, argv + 1, argc - 1);
520 const char **insts = hgc_validate(hgc, argv + 1, argc - 1);
495 int needreconnect = runinstructions(&opts, insts);
521 int needreconnect = runinstructions(&opts, insts);
496 free(insts);
522 free(insts);
497 if (!needreconnect)
523 if (!needreconnect)
498 break;
524 break;
499 hgc_close(hgc);
525 hgc_close(hgc);
500 if (++retry > 10)
526 if (++retry > 10)
501 abortmsg("too many redirections.\n"
527 abortmsg("too many redirections.\n"
502 "Please make sure %s is not a wrapper which "
528 "Please make sure %s is not a wrapper which "
503 "changes sensitive environment variables "
529 "changes sensitive environment variables "
504 "before executing hg. If you have to use a "
530 "before executing hg. If you have to use a "
505 "wrapper, wrap chg instead of hg.",
531 "wrapper, wrap chg instead of hg.",
506 gethgcmd());
532 gethgcmd());
507 }
533 }
508
534
509 setupsignalhandler(hgc_peerpid(hgc), hgc_peerpgid(hgc));
535 setupsignalhandler(hgc_peerpid(hgc), hgc_peerpgid(hgc));
510 atexit(waitpager);
536 atexit(waitpager);
511 int exitcode = hgc_runcommand(hgc, argv + 1, argc - 1);
537 int exitcode = hgc_runcommand(hgc, argv + 1, argc - 1);
512 restoresignalhandler();
538 restoresignalhandler();
513 hgc_close(hgc);
539 hgc_close(hgc);
514 freecmdserveropts(&opts);
540 freecmdserveropts(&opts);
515
541
516 return exitcode;
542 return exitcode;
517 }
543 }
General Comments 0
You need to be logged in to leave comments. Login now