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