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