##// END OF EJS Templates
chgserver: handle ParseError during validate...
Jun Wu -
r28516:3bf2892f default
parent child Browse files
Show More
@@ -0,0 +1,12
1 init repo
2
3 $ hg init foo
4 $ cd foo
5
6 ill-formed config
7
8 $ hg status
9 $ echo '=brokenconfig' >> $HGRCPATH
10 $ hg status
11 hg: parse error at * (glob)
12 [255]
@@ -1,560 +1,565
1 /*
1 /*
2 * A fast client for Mercurial command server
2 * A fast client for Mercurial command server
3 *
3 *
4 * Copyright (c) 2011 Yuya Nishihara <yuya@tcha.org>
4 * Copyright (c) 2011 Yuya Nishihara <yuya@tcha.org>
5 *
5 *
6 * This software may be used and distributed according to the terms of the
6 * This software may be used and distributed according to the terms of the
7 * GNU General Public License version 2 or any later version.
7 * GNU General Public License version 2 or any later version.
8 */
8 */
9
9
10 #include <assert.h>
10 #include <assert.h>
11 #include <errno.h>
11 #include <errno.h>
12 #include <fcntl.h>
12 #include <fcntl.h>
13 #include <signal.h>
13 #include <signal.h>
14 #include <stdio.h>
14 #include <stdio.h>
15 #include <stdlib.h>
15 #include <stdlib.h>
16 #include <string.h>
16 #include <string.h>
17 #include <sys/file.h>
17 #include <sys/file.h>
18 #include <sys/stat.h>
18 #include <sys/stat.h>
19 #include <sys/types.h>
19 #include <sys/types.h>
20 #include <sys/un.h>
20 #include <sys/un.h>
21 #include <sys/wait.h>
21 #include <sys/wait.h>
22 #include <time.h>
22 #include <time.h>
23 #include <unistd.h>
23 #include <unistd.h>
24
24
25 #include "hgclient.h"
25 #include "hgclient.h"
26 #include "util.h"
26 #include "util.h"
27
27
28 #ifndef UNIX_PATH_MAX
28 #ifndef UNIX_PATH_MAX
29 #define UNIX_PATH_MAX (sizeof(((struct sockaddr_un *)NULL)->sun_path))
29 #define UNIX_PATH_MAX (sizeof(((struct sockaddr_un *)NULL)->sun_path))
30 #endif
30 #endif
31
31
32 struct cmdserveropts {
32 struct cmdserveropts {
33 char sockname[UNIX_PATH_MAX];
33 char sockname[UNIX_PATH_MAX];
34 char redirectsockname[UNIX_PATH_MAX];
34 char redirectsockname[UNIX_PATH_MAX];
35 char lockfile[UNIX_PATH_MAX];
35 char lockfile[UNIX_PATH_MAX];
36 size_t argsize;
36 size_t argsize;
37 const char **args;
37 const char **args;
38 int lockfd;
38 int lockfd;
39 };
39 };
40
40
41 static void initcmdserveropts(struct cmdserveropts *opts) {
41 static void initcmdserveropts(struct cmdserveropts *opts) {
42 memset(opts, 0, sizeof(struct cmdserveropts));
42 memset(opts, 0, sizeof(struct cmdserveropts));
43 opts->lockfd = -1;
43 opts->lockfd = -1;
44 }
44 }
45
45
46 static void freecmdserveropts(struct cmdserveropts *opts) {
46 static void freecmdserveropts(struct cmdserveropts *opts) {
47 free(opts->args);
47 free(opts->args);
48 opts->args = NULL;
48 opts->args = NULL;
49 opts->argsize = 0;
49 opts->argsize = 0;
50 }
50 }
51
51
52 /*
52 /*
53 * Test if an argument is a sensitive flag that should be passed to the server.
53 * Test if an argument is a sensitive flag that should be passed to the server.
54 * Return 0 if not, otherwise the number of arguments starting from the current
54 * Return 0 if not, otherwise the number of arguments starting from the current
55 * one that should be passed to the server.
55 * one that should be passed to the server.
56 */
56 */
57 static size_t testsensitiveflag(const char *arg)
57 static size_t testsensitiveflag(const char *arg)
58 {
58 {
59 static const struct {
59 static const struct {
60 const char *name;
60 const char *name;
61 size_t narg;
61 size_t narg;
62 } flags[] = {
62 } flags[] = {
63 {"--config", 1},
63 {"--config", 1},
64 {"--cwd", 1},
64 {"--cwd", 1},
65 {"--repo", 1},
65 {"--repo", 1},
66 {"--repository", 1},
66 {"--repository", 1},
67 {"--traceback", 0},
67 {"--traceback", 0},
68 {"-R", 1},
68 {"-R", 1},
69 };
69 };
70 size_t i;
70 size_t i;
71 for (i = 0; i < sizeof(flags) / sizeof(flags[0]); ++i) {
71 for (i = 0; i < sizeof(flags) / sizeof(flags[0]); ++i) {
72 size_t len = strlen(flags[i].name);
72 size_t len = strlen(flags[i].name);
73 size_t narg = flags[i].narg;
73 size_t narg = flags[i].narg;
74 if (memcmp(arg, flags[i].name, len) == 0) {
74 if (memcmp(arg, flags[i].name, len) == 0) {
75 if (arg[len] == '\0') { /* --flag (value) */
75 if (arg[len] == '\0') { /* --flag (value) */
76 return narg + 1;
76 return narg + 1;
77 } else if (arg[len] == '=' && narg > 0) { /* --flag=value */
77 } else if (arg[len] == '=' && narg > 0) { /* --flag=value */
78 return 1;
78 return 1;
79 } else if (flags[i].name[1] != '-') { /* short flag */
79 } else if (flags[i].name[1] != '-') { /* short flag */
80 return 1;
80 return 1;
81 }
81 }
82 }
82 }
83 }
83 }
84 return 0;
84 return 0;
85 }
85 }
86
86
87 /*
87 /*
88 * Parse argv[] and put sensitive flags to opts->args
88 * Parse argv[] and put sensitive flags to opts->args
89 */
89 */
90 static void setcmdserverargs(struct cmdserveropts *opts,
90 static void setcmdserverargs(struct cmdserveropts *opts,
91 int argc, const char *argv[])
91 int argc, const char *argv[])
92 {
92 {
93 size_t i, step;
93 size_t i, step;
94 opts->argsize = 0;
94 opts->argsize = 0;
95 for (i = 0, step = 1; i < (size_t)argc; i += step, step = 1) {
95 for (i = 0, step = 1; i < (size_t)argc; i += step, step = 1) {
96 if (!argv[i])
96 if (!argv[i])
97 continue; /* pass clang-analyse */
97 continue; /* pass clang-analyse */
98 if (strcmp(argv[i], "--") == 0)
98 if (strcmp(argv[i], "--") == 0)
99 break;
99 break;
100 size_t n = testsensitiveflag(argv[i]);
100 size_t n = testsensitiveflag(argv[i]);
101 if (n == 0 || i + n > (size_t)argc)
101 if (n == 0 || i + n > (size_t)argc)
102 continue;
102 continue;
103 opts->args = reallocx(opts->args,
103 opts->args = reallocx(opts->args,
104 (n + opts->argsize) * sizeof(char *));
104 (n + opts->argsize) * sizeof(char *));
105 memcpy(opts->args + opts->argsize, argv + i,
105 memcpy(opts->args + opts->argsize, argv + i,
106 sizeof(char *) * n);
106 sizeof(char *) * n);
107 opts->argsize += n;
107 opts->argsize += n;
108 step = n;
108 step = n;
109 }
109 }
110 }
110 }
111
111
112 static void preparesockdir(const char *sockdir)
112 static void preparesockdir(const char *sockdir)
113 {
113 {
114 int r;
114 int r;
115 r = mkdir(sockdir, 0700);
115 r = mkdir(sockdir, 0700);
116 if (r < 0 && errno != EEXIST)
116 if (r < 0 && errno != EEXIST)
117 abortmsg("cannot create sockdir %s (errno = %d)",
117 abortmsg("cannot create sockdir %s (errno = %d)",
118 sockdir, errno);
118 sockdir, errno);
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 abortmsg("cannot stat %s (errno = %d)", sockdir, errno);
123 abortmsg("cannot stat %s (errno = %d)", sockdir, errno);
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 static void setcmdserveropts(struct cmdserveropts *opts)
130 static void setcmdserveropts(struct cmdserveropts *opts)
131 {
131 {
132 int r;
132 int r;
133 char sockdir[UNIX_PATH_MAX];
133 char sockdir[UNIX_PATH_MAX];
134 const char *envsockname = getenv("CHGSOCKNAME");
134 const char *envsockname = getenv("CHGSOCKNAME");
135 if (!envsockname) {
135 if (!envsockname) {
136 /* by default, put socket file in secure directory
136 /* by default, put socket file in secure directory
137 * (permission of socket file may be ignored on some Unices) */
137 * (permission of socket file may be ignored on some Unices) */
138 const char *tmpdir = getenv("TMPDIR");
138 const char *tmpdir = getenv("TMPDIR");
139 if (!tmpdir)
139 if (!tmpdir)
140 tmpdir = "/tmp";
140 tmpdir = "/tmp";
141 r = snprintf(sockdir, sizeof(sockdir), "%s/chg%d",
141 r = snprintf(sockdir, sizeof(sockdir), "%s/chg%d",
142 tmpdir, geteuid());
142 tmpdir, geteuid());
143 if (r < 0 || (size_t)r >= sizeof(sockdir))
143 if (r < 0 || (size_t)r >= sizeof(sockdir))
144 abortmsg("too long TMPDIR (r = %d)", r);
144 abortmsg("too long TMPDIR (r = %d)", r);
145 preparesockdir(sockdir);
145 preparesockdir(sockdir);
146 }
146 }
147
147
148 const char *basename = (envsockname) ? envsockname : sockdir;
148 const char *basename = (envsockname) ? envsockname : sockdir;
149 const char *sockfmt = (envsockname) ? "%s" : "%s/server";
149 const char *sockfmt = (envsockname) ? "%s" : "%s/server";
150 const char *lockfmt = (envsockname) ? "%s.lock" : "%s/lock";
150 const char *lockfmt = (envsockname) ? "%s.lock" : "%s/lock";
151 r = snprintf(opts->sockname, sizeof(opts->sockname), sockfmt, basename);
151 r = snprintf(opts->sockname, sizeof(opts->sockname), sockfmt, basename);
152 if (r < 0 || (size_t)r >= sizeof(opts->sockname))
152 if (r < 0 || (size_t)r >= sizeof(opts->sockname))
153 abortmsg("too long TMPDIR or CHGSOCKNAME (r = %d)", r);
153 abortmsg("too long TMPDIR or CHGSOCKNAME (r = %d)", r);
154 r = snprintf(opts->lockfile, sizeof(opts->lockfile), lockfmt, basename);
154 r = snprintf(opts->lockfile, sizeof(opts->lockfile), lockfmt, basename);
155 if (r < 0 || (size_t)r >= sizeof(opts->lockfile))
155 if (r < 0 || (size_t)r >= sizeof(opts->lockfile))
156 abortmsg("too long TMPDIR or CHGSOCKNAME (r = %d)", r);
156 abortmsg("too long TMPDIR or CHGSOCKNAME (r = %d)", r);
157 }
157 }
158
158
159 /*
159 /*
160 * Acquire a file lock that indicates a client is trying to start and connect
160 * Acquire a file lock that indicates a client is trying to start and connect
161 * to a server, before executing a command. The lock is released upon exit or
161 * to a server, before executing a command. The lock is released upon exit or
162 * explicit unlock. Will block if the lock is held by another process.
162 * explicit unlock. Will block if the lock is held by another process.
163 */
163 */
164 static void lockcmdserver(struct cmdserveropts *opts)
164 static void lockcmdserver(struct cmdserveropts *opts)
165 {
165 {
166 if (opts->lockfd == -1) {
166 if (opts->lockfd == -1) {
167 opts->lockfd = open(opts->lockfile, O_RDWR | O_CREAT | O_NOFOLLOW, 0600);
167 opts->lockfd = open(opts->lockfile, O_RDWR | O_CREAT | O_NOFOLLOW, 0600);
168 if (opts->lockfd == -1)
168 if (opts->lockfd == -1)
169 abortmsg("cannot create lock file %s", opts->lockfile);
169 abortmsg("cannot create lock file %s", opts->lockfile);
170 }
170 }
171 int r = flock(opts->lockfd, LOCK_EX);
171 int r = flock(opts->lockfd, LOCK_EX);
172 if (r == -1)
172 if (r == -1)
173 abortmsg("cannot acquire lock");
173 abortmsg("cannot acquire lock");
174 }
174 }
175
175
176 /*
176 /*
177 * Release the file lock held by calling lockcmdserver. Will do nothing if
177 * Release the file lock held by calling lockcmdserver. Will do nothing if
178 * lockcmdserver is not called.
178 * lockcmdserver is not called.
179 */
179 */
180 static void unlockcmdserver(struct cmdserveropts *opts)
180 static void unlockcmdserver(struct cmdserveropts *opts)
181 {
181 {
182 if (opts->lockfd == -1)
182 if (opts->lockfd == -1)
183 return;
183 return;
184 flock(opts->lockfd, LOCK_UN);
184 flock(opts->lockfd, LOCK_UN);
185 close(opts->lockfd);
185 close(opts->lockfd);
186 opts->lockfd = -1;
186 opts->lockfd = -1;
187 }
187 }
188
188
189 static const char *gethgcmd(void)
189 static const char *gethgcmd(void)
190 {
190 {
191 static const char *hgcmd = NULL;
191 static const char *hgcmd = NULL;
192 if (!hgcmd) {
192 if (!hgcmd) {
193 hgcmd = getenv("CHGHG");
193 hgcmd = getenv("CHGHG");
194 if (!hgcmd || hgcmd[0] == '\0')
194 if (!hgcmd || hgcmd[0] == '\0')
195 hgcmd = getenv("HG");
195 hgcmd = getenv("HG");
196 if (!hgcmd || hgcmd[0] == '\0')
196 if (!hgcmd || hgcmd[0] == '\0')
197 hgcmd = "hg";
197 hgcmd = "hg";
198 }
198 }
199 return hgcmd;
199 return hgcmd;
200 }
200 }
201
201
202 static void execcmdserver(const struct cmdserveropts *opts)
202 static void execcmdserver(const struct cmdserveropts *opts)
203 {
203 {
204 const char *hgcmd = gethgcmd();
204 const char *hgcmd = gethgcmd();
205
205
206 const char *baseargv[] = {
206 const char *baseargv[] = {
207 hgcmd,
207 hgcmd,
208 "serve",
208 "serve",
209 "--cmdserver", "chgunix",
209 "--cmdserver", "chgunix",
210 "--address", opts->sockname,
210 "--address", opts->sockname,
211 "--daemon-postexec", "chdir:/",
211 "--daemon-postexec", "chdir:/",
212 "--config", "extensions.chgserver=",
212 "--config", "extensions.chgserver=",
213 };
213 };
214 size_t baseargvsize = sizeof(baseargv) / sizeof(baseargv[0]);
214 size_t baseargvsize = sizeof(baseargv) / sizeof(baseargv[0]);
215 size_t argsize = baseargvsize + opts->argsize + 1;
215 size_t argsize = baseargvsize + opts->argsize + 1;
216
216
217 const char **argv = mallocx(sizeof(char *) * argsize);
217 const char **argv = mallocx(sizeof(char *) * argsize);
218 memcpy(argv, baseargv, sizeof(baseargv));
218 memcpy(argv, baseargv, sizeof(baseargv));
219 memcpy(argv + baseargvsize, opts->args, sizeof(char *) * opts->argsize);
219 memcpy(argv + baseargvsize, opts->args, sizeof(char *) * opts->argsize);
220 argv[argsize - 1] = NULL;
220 argv[argsize - 1] = NULL;
221
221
222 if (putenv("CHGINTERNALMARK=") != 0)
222 if (putenv("CHGINTERNALMARK=") != 0)
223 abortmsg("failed to putenv (errno = %d)", errno);
223 abortmsg("failed to putenv (errno = %d)", errno);
224 if (execvp(hgcmd, (char **)argv) < 0)
224 if (execvp(hgcmd, (char **)argv) < 0)
225 abortmsg("failed to exec cmdserver (errno = %d)", errno);
225 abortmsg("failed to exec cmdserver (errno = %d)", errno);
226 free(argv);
226 free(argv);
227 }
227 }
228
228
229 /* Retry until we can connect to the server. Give up after some time. */
229 /* Retry until we can connect to the server. Give up after some time. */
230 static hgclient_t *retryconnectcmdserver(struct cmdserveropts *opts, pid_t pid)
230 static hgclient_t *retryconnectcmdserver(struct cmdserveropts *opts, pid_t pid)
231 {
231 {
232 static const struct timespec sleepreq = {0, 10 * 1000000};
232 static const struct timespec sleepreq = {0, 10 * 1000000};
233 int pst = 0;
233 int pst = 0;
234
234
235 for (unsigned int i = 0; i < 10 * 100; i++) {
235 for (unsigned int i = 0; i < 10 * 100; i++) {
236 hgclient_t *hgc = hgc_open(opts->sockname);
236 hgclient_t *hgc = hgc_open(opts->sockname);
237 if (hgc)
237 if (hgc)
238 return hgc;
238 return hgc;
239
239
240 if (pid > 0) {
240 if (pid > 0) {
241 /* collect zombie if child process fails to start */
241 /* collect zombie if child process fails to start */
242 int r = waitpid(pid, &pst, WNOHANG);
242 int r = waitpid(pid, &pst, WNOHANG);
243 if (r != 0)
243 if (r != 0)
244 goto cleanup;
244 goto cleanup;
245 }
245 }
246
246
247 nanosleep(&sleepreq, NULL);
247 nanosleep(&sleepreq, NULL);
248 }
248 }
249
249
250 abortmsg("timed out waiting for cmdserver %s", opts->sockname);
250 abortmsg("timed out waiting for cmdserver %s", opts->sockname);
251 return NULL;
251 return NULL;
252
252
253 cleanup:
253 cleanup:
254 if (WIFEXITED(pst)) {
254 if (WIFEXITED(pst)) {
255 debugmsg("cmdserver exited with status %d", WEXITSTATUS(pst));
255 debugmsg("cmdserver exited with status %d", WEXITSTATUS(pst));
256 exit(WEXITSTATUS(pst));
256 exit(WEXITSTATUS(pst));
257 } else if (WIFSIGNALED(pst)) {
257 } else if (WIFSIGNALED(pst)) {
258 abortmsg("cmdserver killed by signal %d", WTERMSIG(pst));
258 abortmsg("cmdserver killed by signal %d", WTERMSIG(pst));
259 } else {
259 } else {
260 abortmsg("error white waiting cmdserver");
260 abortmsg("error white waiting cmdserver");
261 }
261 }
262 return NULL;
262 return NULL;
263 }
263 }
264
264
265 /* Connect to a cmdserver. Will start a new server on demand. */
265 /* Connect to a cmdserver. Will start a new server on demand. */
266 static hgclient_t *connectcmdserver(struct cmdserveropts *opts)
266 static hgclient_t *connectcmdserver(struct cmdserveropts *opts)
267 {
267 {
268 const char *sockname = opts->redirectsockname[0] ?
268 const char *sockname = opts->redirectsockname[0] ?
269 opts->redirectsockname : opts->sockname;
269 opts->redirectsockname : opts->sockname;
270 hgclient_t *hgc = hgc_open(sockname);
270 hgclient_t *hgc = hgc_open(sockname);
271 if (hgc)
271 if (hgc)
272 return hgc;
272 return hgc;
273
273
274 lockcmdserver(opts);
274 lockcmdserver(opts);
275 hgc = hgc_open(sockname);
275 hgc = hgc_open(sockname);
276 if (hgc) {
276 if (hgc) {
277 unlockcmdserver(opts);
277 unlockcmdserver(opts);
278 debugmsg("cmdserver is started by another process");
278 debugmsg("cmdserver is started by another process");
279 return hgc;
279 return hgc;
280 }
280 }
281
281
282 /* prevent us from being connected to an outdated server: we were
282 /* prevent us from being connected to an outdated server: we were
283 * told by a server to redirect to opts->redirectsockname and that
283 * told by a server to redirect to opts->redirectsockname and that
284 * address does not work. we do not want to connect to the server
284 * address does not work. we do not want to connect to the server
285 * again because it will probably tell us the same thing. */
285 * again because it will probably tell us the same thing. */
286 if (sockname == opts->redirectsockname)
286 if (sockname == opts->redirectsockname)
287 unlink(opts->sockname);
287 unlink(opts->sockname);
288
288
289 debugmsg("start cmdserver at %s", opts->sockname);
289 debugmsg("start cmdserver at %s", opts->sockname);
290
290
291 pid_t pid = fork();
291 pid_t pid = fork();
292 if (pid < 0)
292 if (pid < 0)
293 abortmsg("failed to fork cmdserver process");
293 abortmsg("failed to fork cmdserver process");
294 if (pid == 0) {
294 if (pid == 0) {
295 /* do not leak lockfd to hg */
295 /* do not leak lockfd to hg */
296 close(opts->lockfd);
296 close(opts->lockfd);
297 /* bypass uisetup() of pager extension */
297 /* bypass uisetup() of pager extension */
298 int nullfd = open("/dev/null", O_WRONLY);
298 int nullfd = open("/dev/null", O_WRONLY);
299 if (nullfd >= 0) {
299 if (nullfd >= 0) {
300 dup2(nullfd, fileno(stdout));
300 dup2(nullfd, fileno(stdout));
301 close(nullfd);
301 close(nullfd);
302 }
302 }
303 execcmdserver(opts);
303 execcmdserver(opts);
304 } else {
304 } else {
305 hgc = retryconnectcmdserver(opts, pid);
305 hgc = retryconnectcmdserver(opts, pid);
306 }
306 }
307
307
308 unlockcmdserver(opts);
308 unlockcmdserver(opts);
309 return hgc;
309 return hgc;
310 }
310 }
311
311
312 static void killcmdserver(const struct cmdserveropts *opts)
312 static void killcmdserver(const struct cmdserveropts *opts)
313 {
313 {
314 /* resolve config hash */
314 /* resolve config hash */
315 char *resolvedpath = realpath(opts->sockname, NULL);
315 char *resolvedpath = realpath(opts->sockname, NULL);
316 if (resolvedpath) {
316 if (resolvedpath) {
317 unlink(resolvedpath);
317 unlink(resolvedpath);
318 free(resolvedpath);
318 free(resolvedpath);
319 }
319 }
320 }
320 }
321
321
322 static pid_t peerpid = 0;
322 static pid_t peerpid = 0;
323
323
324 static void forwardsignal(int sig)
324 static void forwardsignal(int sig)
325 {
325 {
326 assert(peerpid > 0);
326 assert(peerpid > 0);
327 if (kill(peerpid, sig) < 0)
327 if (kill(peerpid, sig) < 0)
328 abortmsg("cannot kill %d (errno = %d)", peerpid, errno);
328 abortmsg("cannot kill %d (errno = %d)", peerpid, errno);
329 debugmsg("forward signal %d", sig);
329 debugmsg("forward signal %d", sig);
330 }
330 }
331
331
332 static void handlestopsignal(int sig)
332 static void handlestopsignal(int sig)
333 {
333 {
334 sigset_t unblockset, oldset;
334 sigset_t unblockset, oldset;
335 struct sigaction sa, oldsa;
335 struct sigaction sa, oldsa;
336 if (sigemptyset(&unblockset) < 0)
336 if (sigemptyset(&unblockset) < 0)
337 goto error;
337 goto error;
338 if (sigaddset(&unblockset, sig) < 0)
338 if (sigaddset(&unblockset, sig) < 0)
339 goto error;
339 goto error;
340 memset(&sa, 0, sizeof(sa));
340 memset(&sa, 0, sizeof(sa));
341 sa.sa_handler = SIG_DFL;
341 sa.sa_handler = SIG_DFL;
342 sa.sa_flags = SA_RESTART;
342 sa.sa_flags = SA_RESTART;
343 if (sigemptyset(&sa.sa_mask) < 0)
343 if (sigemptyset(&sa.sa_mask) < 0)
344 goto error;
344 goto error;
345
345
346 forwardsignal(sig);
346 forwardsignal(sig);
347 if (raise(sig) < 0) /* resend to self */
347 if (raise(sig) < 0) /* resend to self */
348 goto error;
348 goto error;
349 if (sigaction(sig, &sa, &oldsa) < 0)
349 if (sigaction(sig, &sa, &oldsa) < 0)
350 goto error;
350 goto error;
351 if (sigprocmask(SIG_UNBLOCK, &unblockset, &oldset) < 0)
351 if (sigprocmask(SIG_UNBLOCK, &unblockset, &oldset) < 0)
352 goto error;
352 goto error;
353 /* resent signal will be handled before sigprocmask() returns */
353 /* resent signal will be handled before sigprocmask() returns */
354 if (sigprocmask(SIG_SETMASK, &oldset, NULL) < 0)
354 if (sigprocmask(SIG_SETMASK, &oldset, NULL) < 0)
355 goto error;
355 goto error;
356 if (sigaction(sig, &oldsa, NULL) < 0)
356 if (sigaction(sig, &oldsa, NULL) < 0)
357 goto error;
357 goto error;
358 return;
358 return;
359
359
360 error:
360 error:
361 abortmsg("failed to handle stop signal (errno = %d)", errno);
361 abortmsg("failed to handle stop signal (errno = %d)", errno);
362 }
362 }
363
363
364 static void setupsignalhandler(pid_t pid)
364 static void setupsignalhandler(pid_t pid)
365 {
365 {
366 if (pid <= 0)
366 if (pid <= 0)
367 return;
367 return;
368 peerpid = pid;
368 peerpid = pid;
369
369
370 struct sigaction sa;
370 struct sigaction sa;
371 memset(&sa, 0, sizeof(sa));
371 memset(&sa, 0, sizeof(sa));
372 sa.sa_handler = forwardsignal;
372 sa.sa_handler = forwardsignal;
373 sa.sa_flags = SA_RESTART;
373 sa.sa_flags = SA_RESTART;
374 if (sigemptyset(&sa.sa_mask) < 0)
374 if (sigemptyset(&sa.sa_mask) < 0)
375 goto error;
375 goto error;
376
376
377 if (sigaction(SIGHUP, &sa, NULL) < 0)
377 if (sigaction(SIGHUP, &sa, NULL) < 0)
378 goto error;
378 goto error;
379 if (sigaction(SIGINT, &sa, NULL) < 0)
379 if (sigaction(SIGINT, &sa, NULL) < 0)
380 goto error;
380 goto error;
381
381
382 /* terminate frontend by double SIGTERM in case of server freeze */
382 /* terminate frontend by double SIGTERM in case of server freeze */
383 sa.sa_flags |= SA_RESETHAND;
383 sa.sa_flags |= SA_RESETHAND;
384 if (sigaction(SIGTERM, &sa, NULL) < 0)
384 if (sigaction(SIGTERM, &sa, NULL) < 0)
385 goto error;
385 goto error;
386
386
387 /* propagate job control requests to worker */
387 /* propagate job control requests to worker */
388 sa.sa_handler = forwardsignal;
388 sa.sa_handler = forwardsignal;
389 sa.sa_flags = SA_RESTART;
389 sa.sa_flags = SA_RESTART;
390 if (sigaction(SIGCONT, &sa, NULL) < 0)
390 if (sigaction(SIGCONT, &sa, NULL) < 0)
391 goto error;
391 goto error;
392 sa.sa_handler = handlestopsignal;
392 sa.sa_handler = handlestopsignal;
393 sa.sa_flags = SA_RESTART;
393 sa.sa_flags = SA_RESTART;
394 if (sigaction(SIGTSTP, &sa, NULL) < 0)
394 if (sigaction(SIGTSTP, &sa, NULL) < 0)
395 goto error;
395 goto error;
396
396
397 return;
397 return;
398
398
399 error:
399 error:
400 abortmsg("failed to set up signal handlers (errno = %d)", errno);
400 abortmsg("failed to set up signal handlers (errno = %d)", errno);
401 }
401 }
402
402
403 /* This implementation is based on hgext/pager.py (pre 369741ef7253) */
403 /* This implementation is based on hgext/pager.py (pre 369741ef7253) */
404 static void setuppager(hgclient_t *hgc, const char *const args[],
404 static void setuppager(hgclient_t *hgc, const char *const args[],
405 size_t argsize)
405 size_t argsize)
406 {
406 {
407 const char *pagercmd = hgc_getpager(hgc, args, argsize);
407 const char *pagercmd = hgc_getpager(hgc, args, argsize);
408 if (!pagercmd)
408 if (!pagercmd)
409 return;
409 return;
410
410
411 int pipefds[2];
411 int pipefds[2];
412 if (pipe(pipefds) < 0)
412 if (pipe(pipefds) < 0)
413 return;
413 return;
414 pid_t pid = fork();
414 pid_t pid = fork();
415 if (pid < 0)
415 if (pid < 0)
416 goto error;
416 goto error;
417 if (pid == 0) {
417 if (pid == 0) {
418 close(pipefds[0]);
418 close(pipefds[0]);
419 if (dup2(pipefds[1], fileno(stdout)) < 0)
419 if (dup2(pipefds[1], fileno(stdout)) < 0)
420 goto error;
420 goto error;
421 if (isatty(fileno(stderr))) {
421 if (isatty(fileno(stderr))) {
422 if (dup2(pipefds[1], fileno(stderr)) < 0)
422 if (dup2(pipefds[1], fileno(stderr)) < 0)
423 goto error;
423 goto error;
424 }
424 }
425 close(pipefds[1]);
425 close(pipefds[1]);
426 hgc_attachio(hgc); /* reattach to pager */
426 hgc_attachio(hgc); /* reattach to pager */
427 return;
427 return;
428 } else {
428 } else {
429 dup2(pipefds[0], fileno(stdin));
429 dup2(pipefds[0], fileno(stdin));
430 close(pipefds[0]);
430 close(pipefds[0]);
431 close(pipefds[1]);
431 close(pipefds[1]);
432
432
433 int r = execlp("/bin/sh", "/bin/sh", "-c", pagercmd, NULL);
433 int r = execlp("/bin/sh", "/bin/sh", "-c", pagercmd, NULL);
434 if (r < 0) {
434 if (r < 0) {
435 abortmsg("cannot start pager '%s' (errno = %d)",
435 abortmsg("cannot start pager '%s' (errno = %d)",
436 pagercmd, errno);
436 pagercmd, errno);
437 }
437 }
438 return;
438 return;
439 }
439 }
440
440
441 error:
441 error:
442 close(pipefds[0]);
442 close(pipefds[0]);
443 close(pipefds[1]);
443 close(pipefds[1]);
444 abortmsg("failed to prepare pager (errno = %d)", errno);
444 abortmsg("failed to prepare pager (errno = %d)", errno);
445 }
445 }
446
446
447 /* Run instructions sent from the server like unlink and set redirect path */
447 /* Run instructions sent from the server like unlink and set redirect path */
448 static void runinstructions(struct cmdserveropts *opts, const char **insts)
448 static void runinstructions(struct cmdserveropts *opts, const char **insts)
449 {
449 {
450 assert(insts);
450 assert(insts);
451 opts->redirectsockname[0] = '\0';
451 opts->redirectsockname[0] = '\0';
452 const char **pinst;
452 const char **pinst;
453 for (pinst = insts; *pinst; pinst++) {
453 for (pinst = insts; *pinst; pinst++) {
454 debugmsg("instruction: %s", *pinst);
454 debugmsg("instruction: %s", *pinst);
455 if (strncmp(*pinst, "unlink ", 7) == 0) {
455 if (strncmp(*pinst, "unlink ", 7) == 0) {
456 unlink(*pinst + 7);
456 unlink(*pinst + 7);
457 } else if (strncmp(*pinst, "redirect ", 9) == 0) {
457 } else if (strncmp(*pinst, "redirect ", 9) == 0) {
458 int r = snprintf(opts->redirectsockname,
458 int r = snprintf(opts->redirectsockname,
459 sizeof(opts->redirectsockname),
459 sizeof(opts->redirectsockname),
460 "%s", *pinst + 9);
460 "%s", *pinst + 9);
461 if (r < 0 || r >= (int)sizeof(opts->redirectsockname))
461 if (r < 0 || r >= (int)sizeof(opts->redirectsockname))
462 abortmsg("redirect path is too long (%d)", r);
462 abortmsg("redirect path is too long (%d)", r);
463 } else if (strncmp(*pinst, "exit ", 5) == 0) {
464 int n = 0;
465 if (sscanf(*pinst + 5, "%d", &n) != 1)
466 abortmsg("cannot read the exit code");
467 exit(n);
463 } else {
468 } else {
464 abortmsg("unknown instruction: %s", *pinst);
469 abortmsg("unknown instruction: %s", *pinst);
465 }
470 }
466 }
471 }
467 }
472 }
468
473
469 /*
474 /*
470 * Test whether the command is unsupported or not. This is not designed to
475 * Test whether the command is unsupported or not. This is not designed to
471 * cover all cases. But it's fast, does not depend on the server and does
476 * cover all cases. But it's fast, does not depend on the server and does
472 * not return false positives.
477 * not return false positives.
473 */
478 */
474 static int isunsupported(int argc, const char *argv[])
479 static int isunsupported(int argc, const char *argv[])
475 {
480 {
476 enum {
481 enum {
477 SERVE = 1,
482 SERVE = 1,
478 DAEMON = 2,
483 DAEMON = 2,
479 SERVEDAEMON = SERVE | DAEMON,
484 SERVEDAEMON = SERVE | DAEMON,
480 TIME = 4,
485 TIME = 4,
481 };
486 };
482 unsigned int state = 0;
487 unsigned int state = 0;
483 int i;
488 int i;
484 for (i = 0; i < argc; ++i) {
489 for (i = 0; i < argc; ++i) {
485 if (strcmp(argv[i], "--") == 0)
490 if (strcmp(argv[i], "--") == 0)
486 break;
491 break;
487 if (i == 0 && strcmp("serve", argv[i]) == 0)
492 if (i == 0 && strcmp("serve", argv[i]) == 0)
488 state |= SERVE;
493 state |= SERVE;
489 else if (strcmp("-d", argv[i]) == 0 ||
494 else if (strcmp("-d", argv[i]) == 0 ||
490 strcmp("--daemon", argv[i]) == 0)
495 strcmp("--daemon", argv[i]) == 0)
491 state |= DAEMON;
496 state |= DAEMON;
492 else if (strcmp("--time", argv[i]) == 0)
497 else if (strcmp("--time", argv[i]) == 0)
493 state |= TIME;
498 state |= TIME;
494 }
499 }
495 return (state & TIME) == TIME ||
500 return (state & TIME) == TIME ||
496 (state & SERVEDAEMON) == SERVEDAEMON;
501 (state & SERVEDAEMON) == SERVEDAEMON;
497 }
502 }
498
503
499 static void execoriginalhg(const char *argv[])
504 static void execoriginalhg(const char *argv[])
500 {
505 {
501 debugmsg("execute original hg");
506 debugmsg("execute original hg");
502 if (execvp(gethgcmd(), (char **)argv) < 0)
507 if (execvp(gethgcmd(), (char **)argv) < 0)
503 abortmsg("failed to exec original hg (errno = %d)", errno);
508 abortmsg("failed to exec original hg (errno = %d)", errno);
504 }
509 }
505
510
506 int main(int argc, const char *argv[], const char *envp[])
511 int main(int argc, const char *argv[], const char *envp[])
507 {
512 {
508 if (getenv("CHGDEBUG"))
513 if (getenv("CHGDEBUG"))
509 enabledebugmsg();
514 enabledebugmsg();
510
515
511 if (getenv("CHGINTERNALMARK"))
516 if (getenv("CHGINTERNALMARK"))
512 abortmsg("chg started by chg detected.\n"
517 abortmsg("chg started by chg detected.\n"
513 "Please make sure ${HG:-hg} is not a symlink or "
518 "Please make sure ${HG:-hg} is not a symlink or "
514 "wrapper to chg. Alternatively, set $CHGHG to the "
519 "wrapper to chg. Alternatively, set $CHGHG to the "
515 "path of real hg.");
520 "path of real hg.");
516
521
517 if (isunsupported(argc - 1, argv + 1))
522 if (isunsupported(argc - 1, argv + 1))
518 execoriginalhg(argv);
523 execoriginalhg(argv);
519
524
520 struct cmdserveropts opts;
525 struct cmdserveropts opts;
521 initcmdserveropts(&opts);
526 initcmdserveropts(&opts);
522 setcmdserveropts(&opts);
527 setcmdserveropts(&opts);
523 setcmdserverargs(&opts, argc, argv);
528 setcmdserverargs(&opts, argc, argv);
524
529
525 if (argc == 2) {
530 if (argc == 2) {
526 if (strcmp(argv[1], "--kill-chg-daemon") == 0) {
531 if (strcmp(argv[1], "--kill-chg-daemon") == 0) {
527 killcmdserver(&opts);
532 killcmdserver(&opts);
528 return 0;
533 return 0;
529 }
534 }
530 }
535 }
531
536
532 hgclient_t *hgc;
537 hgclient_t *hgc;
533 size_t retry = 0;
538 size_t retry = 0;
534 while (1) {
539 while (1) {
535 hgc = connectcmdserver(&opts);
540 hgc = connectcmdserver(&opts);
536 if (!hgc)
541 if (!hgc)
537 abortmsg("cannot open hg client");
542 abortmsg("cannot open hg client");
538 hgc_setenv(hgc, envp);
543 hgc_setenv(hgc, envp);
539 const char **insts = hgc_validate(hgc, argv + 1, argc - 1);
544 const char **insts = hgc_validate(hgc, argv + 1, argc - 1);
540 if (insts == NULL)
545 if (insts == NULL)
541 break;
546 break;
542 runinstructions(&opts, insts);
547 runinstructions(&opts, insts);
543 free(insts);
548 free(insts);
544 hgc_close(hgc);
549 hgc_close(hgc);
545 if (++retry > 10)
550 if (++retry > 10)
546 abortmsg("too many redirections.\n"
551 abortmsg("too many redirections.\n"
547 "Please make sure %s is not a wrapper which "
552 "Please make sure %s is not a wrapper which "
548 "changes sensitive environment variables "
553 "changes sensitive environment variables "
549 "before executing hg. If you have to use a "
554 "before executing hg. If you have to use a "
550 "wrapper, wrap chg instead of hg.",
555 "wrapper, wrap chg instead of hg.",
551 gethgcmd());
556 gethgcmd());
552 }
557 }
553
558
554 setupsignalhandler(hgc_peerpid(hgc));
559 setupsignalhandler(hgc_peerpid(hgc));
555 setuppager(hgc, argv + 1, argc - 1);
560 setuppager(hgc, argv + 1, argc - 1);
556 int exitcode = hgc_runcommand(hgc, argv + 1, argc - 1);
561 int exitcode = hgc_runcommand(hgc, argv + 1, argc - 1);
557 hgc_close(hgc);
562 hgc_close(hgc);
558 freecmdserveropts(&opts);
563 freecmdserveropts(&opts);
559 return exitcode;
564 return exitcode;
560 }
565 }
@@ -1,663 +1,671
1 # chgserver.py - command server extension for cHg
1 # chgserver.py - command server extension for cHg
2 #
2 #
3 # Copyright 2011 Yuya Nishihara <yuya@tcha.org>
3 # Copyright 2011 Yuya Nishihara <yuya@tcha.org>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 """command server extension for cHg (EXPERIMENTAL)
8 """command server extension for cHg (EXPERIMENTAL)
9
9
10 'S' channel (read/write)
10 'S' channel (read/write)
11 propagate ui.system() request to client
11 propagate ui.system() request to client
12
12
13 'attachio' command
13 'attachio' command
14 attach client's stdio passed by sendmsg()
14 attach client's stdio passed by sendmsg()
15
15
16 'chdir' command
16 'chdir' command
17 change current directory
17 change current directory
18
18
19 'getpager' command
19 'getpager' command
20 checks if pager is enabled and which pager should be executed
20 checks if pager is enabled and which pager should be executed
21
21
22 'setenv' command
22 'setenv' command
23 replace os.environ completely
23 replace os.environ completely
24
24
25 'setumask' command
25 'setumask' command
26 set umask
26 set umask
27
27
28 'validate' command
28 'validate' command
29 reload the config and check if the server is up to date
29 reload the config and check if the server is up to date
30
30
31 Config
31 Config
32 ------
32 ------
33
33
34 ::
34 ::
35
35
36 [chgserver]
36 [chgserver]
37 idletimeout = 3600 # seconds, after which an idle server will exit
37 idletimeout = 3600 # seconds, after which an idle server will exit
38 skiphash = False # whether to skip config or env change checks
38 skiphash = False # whether to skip config or env change checks
39 """
39 """
40
40
41 from __future__ import absolute_import
41 from __future__ import absolute_import
42
42
43 import SocketServer
43 import SocketServer
44 import errno
44 import errno
45 import inspect
45 import inspect
46 import os
46 import os
47 import re
47 import re
48 import struct
48 import struct
49 import sys
49 import sys
50 import threading
50 import threading
51 import time
51 import time
52 import traceback
52 import traceback
53
53
54 from mercurial.i18n import _
54 from mercurial.i18n import _
55
55
56 from mercurial import (
56 from mercurial import (
57 cmdutil,
57 cmdutil,
58 commands,
58 commands,
59 commandserver,
59 commandserver,
60 dispatch,
60 dispatch,
61 error,
61 error,
62 extensions,
62 extensions,
63 osutil,
63 osutil,
64 util,
64 util,
65 )
65 )
66
66
67 # Note for extension authors: ONLY specify testedwith = 'internal' for
67 # Note for extension authors: ONLY specify testedwith = 'internal' for
68 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
68 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
69 # be specifying the version(s) of Mercurial they are tested with, or
69 # be specifying the version(s) of Mercurial they are tested with, or
70 # leave the attribute unspecified.
70 # leave the attribute unspecified.
71 testedwith = 'internal'
71 testedwith = 'internal'
72
72
73 _log = commandserver.log
73 _log = commandserver.log
74
74
75 def _hashlist(items):
75 def _hashlist(items):
76 """return sha1 hexdigest for a list"""
76 """return sha1 hexdigest for a list"""
77 return util.sha1(str(items)).hexdigest()
77 return util.sha1(str(items)).hexdigest()
78
78
79 # sensitive config sections affecting confighash
79 # sensitive config sections affecting confighash
80 _configsections = [
80 _configsections = [
81 'extdiff', # uisetup will register new commands
81 'extdiff', # uisetup will register new commands
82 'extensions',
82 'extensions',
83 ]
83 ]
84
84
85 # sensitive environment variables affecting confighash
85 # sensitive environment variables affecting confighash
86 _envre = re.compile(r'''\A(?:
86 _envre = re.compile(r'''\A(?:
87 CHGHG
87 CHGHG
88 |HG.*
88 |HG.*
89 |LANG(?:UAGE)?
89 |LANG(?:UAGE)?
90 |LC_.*
90 |LC_.*
91 |LD_.*
91 |LD_.*
92 |PATH
92 |PATH
93 |PYTHON.*
93 |PYTHON.*
94 |TERM(?:INFO)?
94 |TERM(?:INFO)?
95 |TZ
95 |TZ
96 )\Z''', re.X)
96 )\Z''', re.X)
97
97
98 def _confighash(ui):
98 def _confighash(ui):
99 """return a quick hash for detecting config/env changes
99 """return a quick hash for detecting config/env changes
100
100
101 confighash is the hash of sensitive config items and environment variables.
101 confighash is the hash of sensitive config items and environment variables.
102
102
103 for chgserver, it is designed that once confighash changes, the server is
103 for chgserver, it is designed that once confighash changes, the server is
104 not qualified to serve its client and should redirect the client to a new
104 not qualified to serve its client and should redirect the client to a new
105 server. different from mtimehash, confighash change will not mark the
105 server. different from mtimehash, confighash change will not mark the
106 server outdated and exit since the user can have different configs at the
106 server outdated and exit since the user can have different configs at the
107 same time.
107 same time.
108 """
108 """
109 sectionitems = []
109 sectionitems = []
110 for section in _configsections:
110 for section in _configsections:
111 sectionitems.append(ui.configitems(section))
111 sectionitems.append(ui.configitems(section))
112 sectionhash = _hashlist(sectionitems)
112 sectionhash = _hashlist(sectionitems)
113 envitems = [(k, v) for k, v in os.environ.iteritems() if _envre.match(k)]
113 envitems = [(k, v) for k, v in os.environ.iteritems() if _envre.match(k)]
114 envhash = _hashlist(sorted(envitems))
114 envhash = _hashlist(sorted(envitems))
115 return sectionhash[:6] + envhash[:6]
115 return sectionhash[:6] + envhash[:6]
116
116
117 def _getmtimepaths(ui):
117 def _getmtimepaths(ui):
118 """get a list of paths that should be checked to detect change
118 """get a list of paths that should be checked to detect change
119
119
120 The list will include:
120 The list will include:
121 - extensions (will not cover all files for complex extensions)
121 - extensions (will not cover all files for complex extensions)
122 - mercurial/__version__.py
122 - mercurial/__version__.py
123 - python binary
123 - python binary
124 """
124 """
125 modules = [m for n, m in extensions.extensions(ui)]
125 modules = [m for n, m in extensions.extensions(ui)]
126 try:
126 try:
127 from mercurial import __version__
127 from mercurial import __version__
128 modules.append(__version__)
128 modules.append(__version__)
129 except ImportError:
129 except ImportError:
130 pass
130 pass
131 files = [sys.executable]
131 files = [sys.executable]
132 for m in modules:
132 for m in modules:
133 try:
133 try:
134 files.append(inspect.getabsfile(m))
134 files.append(inspect.getabsfile(m))
135 except TypeError:
135 except TypeError:
136 pass
136 pass
137 return sorted(set(files))
137 return sorted(set(files))
138
138
139 def _mtimehash(paths):
139 def _mtimehash(paths):
140 """return a quick hash for detecting file changes
140 """return a quick hash for detecting file changes
141
141
142 mtimehash calls stat on given paths and calculate a hash based on size and
142 mtimehash calls stat on given paths and calculate a hash based on size and
143 mtime of each file. mtimehash does not read file content because reading is
143 mtime of each file. mtimehash does not read file content because reading is
144 expensive. therefore it's not 100% reliable for detecting content changes.
144 expensive. therefore it's not 100% reliable for detecting content changes.
145 it's possible to return different hashes for same file contents.
145 it's possible to return different hashes for same file contents.
146 it's also possible to return a same hash for different file contents for
146 it's also possible to return a same hash for different file contents for
147 some carefully crafted situation.
147 some carefully crafted situation.
148
148
149 for chgserver, it is designed that once mtimehash changes, the server is
149 for chgserver, it is designed that once mtimehash changes, the server is
150 considered outdated immediately and should no longer provide service.
150 considered outdated immediately and should no longer provide service.
151 """
151 """
152 def trystat(path):
152 def trystat(path):
153 try:
153 try:
154 st = os.stat(path)
154 st = os.stat(path)
155 return (st.st_mtime, st.st_size)
155 return (st.st_mtime, st.st_size)
156 except OSError:
156 except OSError:
157 # could be ENOENT, EPERM etc. not fatal in any case
157 # could be ENOENT, EPERM etc. not fatal in any case
158 pass
158 pass
159 return _hashlist(map(trystat, paths))[:12]
159 return _hashlist(map(trystat, paths))[:12]
160
160
161 class hashstate(object):
161 class hashstate(object):
162 """a structure storing confighash, mtimehash, paths used for mtimehash"""
162 """a structure storing confighash, mtimehash, paths used for mtimehash"""
163 def __init__(self, confighash, mtimehash, mtimepaths):
163 def __init__(self, confighash, mtimehash, mtimepaths):
164 self.confighash = confighash
164 self.confighash = confighash
165 self.mtimehash = mtimehash
165 self.mtimehash = mtimehash
166 self.mtimepaths = mtimepaths
166 self.mtimepaths = mtimepaths
167
167
168 @staticmethod
168 @staticmethod
169 def fromui(ui, mtimepaths=None):
169 def fromui(ui, mtimepaths=None):
170 if mtimepaths is None:
170 if mtimepaths is None:
171 mtimepaths = _getmtimepaths(ui)
171 mtimepaths = _getmtimepaths(ui)
172 confighash = _confighash(ui)
172 confighash = _confighash(ui)
173 mtimehash = _mtimehash(mtimepaths)
173 mtimehash = _mtimehash(mtimepaths)
174 _log('confighash = %s mtimehash = %s\n' % (confighash, mtimehash))
174 _log('confighash = %s mtimehash = %s\n' % (confighash, mtimehash))
175 return hashstate(confighash, mtimehash, mtimepaths)
175 return hashstate(confighash, mtimehash, mtimepaths)
176
176
177 # copied from hgext/pager.py:uisetup()
177 # copied from hgext/pager.py:uisetup()
178 def _setuppagercmd(ui, options, cmd):
178 def _setuppagercmd(ui, options, cmd):
179 if not ui.formatted():
179 if not ui.formatted():
180 return
180 return
181
181
182 p = ui.config("pager", "pager", os.environ.get("PAGER"))
182 p = ui.config("pager", "pager", os.environ.get("PAGER"))
183 usepager = False
183 usepager = False
184 always = util.parsebool(options['pager'])
184 always = util.parsebool(options['pager'])
185 auto = options['pager'] == 'auto'
185 auto = options['pager'] == 'auto'
186
186
187 if not p:
187 if not p:
188 pass
188 pass
189 elif always:
189 elif always:
190 usepager = True
190 usepager = True
191 elif not auto:
191 elif not auto:
192 usepager = False
192 usepager = False
193 else:
193 else:
194 attended = ['annotate', 'cat', 'diff', 'export', 'glog', 'log', 'qdiff']
194 attended = ['annotate', 'cat', 'diff', 'export', 'glog', 'log', 'qdiff']
195 attend = ui.configlist('pager', 'attend', attended)
195 attend = ui.configlist('pager', 'attend', attended)
196 ignore = ui.configlist('pager', 'ignore')
196 ignore = ui.configlist('pager', 'ignore')
197 cmds, _ = cmdutil.findcmd(cmd, commands.table)
197 cmds, _ = cmdutil.findcmd(cmd, commands.table)
198
198
199 for cmd in cmds:
199 for cmd in cmds:
200 var = 'attend-%s' % cmd
200 var = 'attend-%s' % cmd
201 if ui.config('pager', var):
201 if ui.config('pager', var):
202 usepager = ui.configbool('pager', var)
202 usepager = ui.configbool('pager', var)
203 break
203 break
204 if (cmd in attend or
204 if (cmd in attend or
205 (cmd not in ignore and not attend)):
205 (cmd not in ignore and not attend)):
206 usepager = True
206 usepager = True
207 break
207 break
208
208
209 if usepager:
209 if usepager:
210 ui.setconfig('ui', 'formatted', ui.formatted(), 'pager')
210 ui.setconfig('ui', 'formatted', ui.formatted(), 'pager')
211 ui.setconfig('ui', 'interactive', False, 'pager')
211 ui.setconfig('ui', 'interactive', False, 'pager')
212 return p
212 return p
213
213
214 _envvarre = re.compile(r'\$[a-zA-Z_]+')
214 _envvarre = re.compile(r'\$[a-zA-Z_]+')
215
215
216 def _clearenvaliases(cmdtable):
216 def _clearenvaliases(cmdtable):
217 """Remove stale command aliases referencing env vars; variable expansion
217 """Remove stale command aliases referencing env vars; variable expansion
218 is done at dispatch.addaliases()"""
218 is done at dispatch.addaliases()"""
219 for name, tab in cmdtable.items():
219 for name, tab in cmdtable.items():
220 cmddef = tab[0]
220 cmddef = tab[0]
221 if (isinstance(cmddef, dispatch.cmdalias) and
221 if (isinstance(cmddef, dispatch.cmdalias) and
222 not cmddef.definition.startswith('!') and # shell alias
222 not cmddef.definition.startswith('!') and # shell alias
223 _envvarre.search(cmddef.definition)):
223 _envvarre.search(cmddef.definition)):
224 del cmdtable[name]
224 del cmdtable[name]
225
225
226 def _newchgui(srcui, csystem):
226 def _newchgui(srcui, csystem):
227 class chgui(srcui.__class__):
227 class chgui(srcui.__class__):
228 def __init__(self, src=None):
228 def __init__(self, src=None):
229 super(chgui, self).__init__(src)
229 super(chgui, self).__init__(src)
230 if src:
230 if src:
231 self._csystem = getattr(src, '_csystem', csystem)
231 self._csystem = getattr(src, '_csystem', csystem)
232 else:
232 else:
233 self._csystem = csystem
233 self._csystem = csystem
234
234
235 def system(self, cmd, environ=None, cwd=None, onerr=None,
235 def system(self, cmd, environ=None, cwd=None, onerr=None,
236 errprefix=None):
236 errprefix=None):
237 # copied from mercurial/util.py:system()
237 # copied from mercurial/util.py:system()
238 self.flush()
238 self.flush()
239 def py2shell(val):
239 def py2shell(val):
240 if val is None or val is False:
240 if val is None or val is False:
241 return '0'
241 return '0'
242 if val is True:
242 if val is True:
243 return '1'
243 return '1'
244 return str(val)
244 return str(val)
245 env = os.environ.copy()
245 env = os.environ.copy()
246 if environ:
246 if environ:
247 env.update((k, py2shell(v)) for k, v in environ.iteritems())
247 env.update((k, py2shell(v)) for k, v in environ.iteritems())
248 env['HG'] = util.hgexecutable()
248 env['HG'] = util.hgexecutable()
249 rc = self._csystem(cmd, env, cwd)
249 rc = self._csystem(cmd, env, cwd)
250 if rc and onerr:
250 if rc and onerr:
251 errmsg = '%s %s' % (os.path.basename(cmd.split(None, 1)[0]),
251 errmsg = '%s %s' % (os.path.basename(cmd.split(None, 1)[0]),
252 util.explainexit(rc)[0])
252 util.explainexit(rc)[0])
253 if errprefix:
253 if errprefix:
254 errmsg = '%s: %s' % (errprefix, errmsg)
254 errmsg = '%s: %s' % (errprefix, errmsg)
255 raise onerr(errmsg)
255 raise onerr(errmsg)
256 return rc
256 return rc
257
257
258 return chgui(srcui)
258 return chgui(srcui)
259
259
260 def _renewui(srcui, args=None):
260 def _renewui(srcui, args=None):
261 if not args:
261 if not args:
262 args = []
262 args = []
263
263
264 newui = srcui.__class__()
264 newui = srcui.__class__()
265 for a in ['fin', 'fout', 'ferr', 'environ']:
265 for a in ['fin', 'fout', 'ferr', 'environ']:
266 setattr(newui, a, getattr(srcui, a))
266 setattr(newui, a, getattr(srcui, a))
267 if util.safehasattr(srcui, '_csystem'):
267 if util.safehasattr(srcui, '_csystem'):
268 newui._csystem = srcui._csystem
268 newui._csystem = srcui._csystem
269
269
270 # load wd and repo config, copied from dispatch.py
270 # load wd and repo config, copied from dispatch.py
271 cwds = dispatch._earlygetopt(['--cwd'], args)
271 cwds = dispatch._earlygetopt(['--cwd'], args)
272 cwd = cwds and os.path.realpath(cwds[-1]) or None
272 cwd = cwds and os.path.realpath(cwds[-1]) or None
273 rpath = dispatch._earlygetopt(["-R", "--repository", "--repo"], args)
273 rpath = dispatch._earlygetopt(["-R", "--repository", "--repo"], args)
274 path, newui = dispatch._getlocal(newui, rpath, wd=cwd)
274 path, newui = dispatch._getlocal(newui, rpath, wd=cwd)
275
275
276 # internal config: extensions.chgserver
276 # internal config: extensions.chgserver
277 # copy it. it can only be overrided from command line.
277 # copy it. it can only be overrided from command line.
278 newui.setconfig('extensions', 'chgserver',
278 newui.setconfig('extensions', 'chgserver',
279 srcui.config('extensions', 'chgserver'), '--config')
279 srcui.config('extensions', 'chgserver'), '--config')
280
280
281 # command line args
281 # command line args
282 dispatch._parseconfig(newui, dispatch._earlygetopt(['--config'], args))
282 dispatch._parseconfig(newui, dispatch._earlygetopt(['--config'], args))
283
283
284 # stolen from tortoisehg.util.copydynamicconfig()
284 # stolen from tortoisehg.util.copydynamicconfig()
285 for section, name, value in srcui.walkconfig():
285 for section, name, value in srcui.walkconfig():
286 source = srcui.configsource(section, name)
286 source = srcui.configsource(section, name)
287 if ':' in source or source == '--config':
287 if ':' in source or source == '--config':
288 # path:line or command line
288 # path:line or command line
289 continue
289 continue
290 if source == 'none':
290 if source == 'none':
291 # ui.configsource returns 'none' by default
291 # ui.configsource returns 'none' by default
292 source = ''
292 source = ''
293 newui.setconfig(section, name, value, source)
293 newui.setconfig(section, name, value, source)
294 return newui
294 return newui
295
295
296 class channeledsystem(object):
296 class channeledsystem(object):
297 """Propagate ui.system() request in the following format:
297 """Propagate ui.system() request in the following format:
298
298
299 payload length (unsigned int),
299 payload length (unsigned int),
300 cmd, '\0',
300 cmd, '\0',
301 cwd, '\0',
301 cwd, '\0',
302 envkey, '=', val, '\0',
302 envkey, '=', val, '\0',
303 ...
303 ...
304 envkey, '=', val
304 envkey, '=', val
305
305
306 and waits:
306 and waits:
307
307
308 exitcode length (unsigned int),
308 exitcode length (unsigned int),
309 exitcode (int)
309 exitcode (int)
310 """
310 """
311 def __init__(self, in_, out, channel):
311 def __init__(self, in_, out, channel):
312 self.in_ = in_
312 self.in_ = in_
313 self.out = out
313 self.out = out
314 self.channel = channel
314 self.channel = channel
315
315
316 def __call__(self, cmd, environ, cwd):
316 def __call__(self, cmd, environ, cwd):
317 args = [util.quotecommand(cmd), os.path.abspath(cwd or '.')]
317 args = [util.quotecommand(cmd), os.path.abspath(cwd or '.')]
318 args.extend('%s=%s' % (k, v) for k, v in environ.iteritems())
318 args.extend('%s=%s' % (k, v) for k, v in environ.iteritems())
319 data = '\0'.join(args)
319 data = '\0'.join(args)
320 self.out.write(struct.pack('>cI', self.channel, len(data)))
320 self.out.write(struct.pack('>cI', self.channel, len(data)))
321 self.out.write(data)
321 self.out.write(data)
322 self.out.flush()
322 self.out.flush()
323
323
324 length = self.in_.read(4)
324 length = self.in_.read(4)
325 length, = struct.unpack('>I', length)
325 length, = struct.unpack('>I', length)
326 if length != 4:
326 if length != 4:
327 raise error.Abort(_('invalid response'))
327 raise error.Abort(_('invalid response'))
328 rc, = struct.unpack('>i', self.in_.read(4))
328 rc, = struct.unpack('>i', self.in_.read(4))
329 return rc
329 return rc
330
330
331 _iochannels = [
331 _iochannels = [
332 # server.ch, ui.fp, mode
332 # server.ch, ui.fp, mode
333 ('cin', 'fin', 'rb'),
333 ('cin', 'fin', 'rb'),
334 ('cout', 'fout', 'wb'),
334 ('cout', 'fout', 'wb'),
335 ('cerr', 'ferr', 'wb'),
335 ('cerr', 'ferr', 'wb'),
336 ]
336 ]
337
337
338 class chgcmdserver(commandserver.server):
338 class chgcmdserver(commandserver.server):
339 def __init__(self, ui, repo, fin, fout, sock, hashstate, baseaddress):
339 def __init__(self, ui, repo, fin, fout, sock, hashstate, baseaddress):
340 super(chgcmdserver, self).__init__(
340 super(chgcmdserver, self).__init__(
341 _newchgui(ui, channeledsystem(fin, fout, 'S')), repo, fin, fout)
341 _newchgui(ui, channeledsystem(fin, fout, 'S')), repo, fin, fout)
342 self.clientsock = sock
342 self.clientsock = sock
343 self._oldios = [] # original (self.ch, ui.fp, fd) before "attachio"
343 self._oldios = [] # original (self.ch, ui.fp, fd) before "attachio"
344 self.hashstate = hashstate
344 self.hashstate = hashstate
345 self.baseaddress = baseaddress
345 self.baseaddress = baseaddress
346 if hashstate is not None:
346 if hashstate is not None:
347 self.capabilities = self.capabilities.copy()
347 self.capabilities = self.capabilities.copy()
348 self.capabilities['validate'] = chgcmdserver.validate
348 self.capabilities['validate'] = chgcmdserver.validate
349
349
350 def cleanup(self):
350 def cleanup(self):
351 # dispatch._runcatch() does not flush outputs if exception is not
351 # dispatch._runcatch() does not flush outputs if exception is not
352 # handled by dispatch._dispatch()
352 # handled by dispatch._dispatch()
353 self.ui.flush()
353 self.ui.flush()
354 self._restoreio()
354 self._restoreio()
355
355
356 def attachio(self):
356 def attachio(self):
357 """Attach to client's stdio passed via unix domain socket; all
357 """Attach to client's stdio passed via unix domain socket; all
358 channels except cresult will no longer be used
358 channels except cresult will no longer be used
359 """
359 """
360 # tell client to sendmsg() with 1-byte payload, which makes it
360 # tell client to sendmsg() with 1-byte payload, which makes it
361 # distinctive from "attachio\n" command consumed by client.read()
361 # distinctive from "attachio\n" command consumed by client.read()
362 self.clientsock.sendall(struct.pack('>cI', 'I', 1))
362 self.clientsock.sendall(struct.pack('>cI', 'I', 1))
363 clientfds = osutil.recvfds(self.clientsock.fileno())
363 clientfds = osutil.recvfds(self.clientsock.fileno())
364 _log('received fds: %r\n' % clientfds)
364 _log('received fds: %r\n' % clientfds)
365
365
366 ui = self.ui
366 ui = self.ui
367 ui.flush()
367 ui.flush()
368 first = self._saveio()
368 first = self._saveio()
369 for fd, (cn, fn, mode) in zip(clientfds, _iochannels):
369 for fd, (cn, fn, mode) in zip(clientfds, _iochannels):
370 assert fd > 0
370 assert fd > 0
371 fp = getattr(ui, fn)
371 fp = getattr(ui, fn)
372 os.dup2(fd, fp.fileno())
372 os.dup2(fd, fp.fileno())
373 os.close(fd)
373 os.close(fd)
374 if not first:
374 if not first:
375 continue
375 continue
376 # reset buffering mode when client is first attached. as we want
376 # reset buffering mode when client is first attached. as we want
377 # to see output immediately on pager, the mode stays unchanged
377 # to see output immediately on pager, the mode stays unchanged
378 # when client re-attached. ferr is unchanged because it should
378 # when client re-attached. ferr is unchanged because it should
379 # be unbuffered no matter if it is a tty or not.
379 # be unbuffered no matter if it is a tty or not.
380 if fn == 'ferr':
380 if fn == 'ferr':
381 newfp = fp
381 newfp = fp
382 else:
382 else:
383 # make it line buffered explicitly because the default is
383 # make it line buffered explicitly because the default is
384 # decided on first write(), where fout could be a pager.
384 # decided on first write(), where fout could be a pager.
385 if fp.isatty():
385 if fp.isatty():
386 bufsize = 1 # line buffered
386 bufsize = 1 # line buffered
387 else:
387 else:
388 bufsize = -1 # system default
388 bufsize = -1 # system default
389 newfp = os.fdopen(fp.fileno(), mode, bufsize)
389 newfp = os.fdopen(fp.fileno(), mode, bufsize)
390 setattr(ui, fn, newfp)
390 setattr(ui, fn, newfp)
391 setattr(self, cn, newfp)
391 setattr(self, cn, newfp)
392
392
393 self.cresult.write(struct.pack('>i', len(clientfds)))
393 self.cresult.write(struct.pack('>i', len(clientfds)))
394
394
395 def _saveio(self):
395 def _saveio(self):
396 if self._oldios:
396 if self._oldios:
397 return False
397 return False
398 ui = self.ui
398 ui = self.ui
399 for cn, fn, _mode in _iochannels:
399 for cn, fn, _mode in _iochannels:
400 ch = getattr(self, cn)
400 ch = getattr(self, cn)
401 fp = getattr(ui, fn)
401 fp = getattr(ui, fn)
402 fd = os.dup(fp.fileno())
402 fd = os.dup(fp.fileno())
403 self._oldios.append((ch, fp, fd))
403 self._oldios.append((ch, fp, fd))
404 return True
404 return True
405
405
406 def _restoreio(self):
406 def _restoreio(self):
407 ui = self.ui
407 ui = self.ui
408 for (ch, fp, fd), (cn, fn, _mode) in zip(self._oldios, _iochannels):
408 for (ch, fp, fd), (cn, fn, _mode) in zip(self._oldios, _iochannels):
409 newfp = getattr(ui, fn)
409 newfp = getattr(ui, fn)
410 # close newfp while it's associated with client; otherwise it
410 # close newfp while it's associated with client; otherwise it
411 # would be closed when newfp is deleted
411 # would be closed when newfp is deleted
412 if newfp is not fp:
412 if newfp is not fp:
413 newfp.close()
413 newfp.close()
414 # restore original fd: fp is open again
414 # restore original fd: fp is open again
415 os.dup2(fd, fp.fileno())
415 os.dup2(fd, fp.fileno())
416 os.close(fd)
416 os.close(fd)
417 setattr(self, cn, ch)
417 setattr(self, cn, ch)
418 setattr(ui, fn, fp)
418 setattr(ui, fn, fp)
419 del self._oldios[:]
419 del self._oldios[:]
420
420
421 def validate(self):
421 def validate(self):
422 """Reload the config and check if the server is up to date
422 """Reload the config and check if the server is up to date
423
423
424 Read a list of '\0' separated arguments.
424 Read a list of '\0' separated arguments.
425 Write a non-empty list of '\0' separated instruction strings or '\0'
425 Write a non-empty list of '\0' separated instruction strings or '\0'
426 if the list is empty.
426 if the list is empty.
427 An instruction string could be either:
427 An instruction string could be either:
428 - "unlink $path", the client should unlink the path to stop the
428 - "unlink $path", the client should unlink the path to stop the
429 outdated server.
429 outdated server.
430 - "redirect $path", the client should try to connect to another
430 - "redirect $path", the client should try to connect to another
431 server instead.
431 server instead.
432 - "exit $n", the client should exit directly with code n.
433 This may happen if we cannot parse the config.
432 """
434 """
433 args = self._readlist()
435 args = self._readlist()
434 self.ui = _renewui(self.ui, args)
436 try:
437 self.ui = _renewui(self.ui, args)
438 except error.ParseError as inst:
439 dispatch._formatparse(self.ui.warn, inst)
440 self.ui.flush()
441 self.cresult.write('exit 255')
442 return
435 newhash = hashstate.fromui(self.ui, self.hashstate.mtimepaths)
443 newhash = hashstate.fromui(self.ui, self.hashstate.mtimepaths)
436 insts = []
444 insts = []
437 if newhash.mtimehash != self.hashstate.mtimehash:
445 if newhash.mtimehash != self.hashstate.mtimehash:
438 addr = _hashaddress(self.baseaddress, self.hashstate.confighash)
446 addr = _hashaddress(self.baseaddress, self.hashstate.confighash)
439 insts.append('unlink %s' % addr)
447 insts.append('unlink %s' % addr)
440 if newhash.confighash != self.hashstate.confighash:
448 if newhash.confighash != self.hashstate.confighash:
441 addr = _hashaddress(self.baseaddress, newhash.confighash)
449 addr = _hashaddress(self.baseaddress, newhash.confighash)
442 insts.append('redirect %s' % addr)
450 insts.append('redirect %s' % addr)
443 _log('validate: %s\n' % insts)
451 _log('validate: %s\n' % insts)
444 self.cresult.write('\0'.join(insts) or '\0')
452 self.cresult.write('\0'.join(insts) or '\0')
445
453
446 def chdir(self):
454 def chdir(self):
447 """Change current directory
455 """Change current directory
448
456
449 Note that the behavior of --cwd option is bit different from this.
457 Note that the behavior of --cwd option is bit different from this.
450 It does not affect --config parameter.
458 It does not affect --config parameter.
451 """
459 """
452 path = self._readstr()
460 path = self._readstr()
453 if not path:
461 if not path:
454 return
462 return
455 _log('chdir to %r\n' % path)
463 _log('chdir to %r\n' % path)
456 os.chdir(path)
464 os.chdir(path)
457
465
458 def setumask(self):
466 def setumask(self):
459 """Change umask"""
467 """Change umask"""
460 mask = struct.unpack('>I', self._read(4))[0]
468 mask = struct.unpack('>I', self._read(4))[0]
461 _log('setumask %r\n' % mask)
469 _log('setumask %r\n' % mask)
462 os.umask(mask)
470 os.umask(mask)
463
471
464 def getpager(self):
472 def getpager(self):
465 """Read cmdargs and write pager command to r-channel if enabled
473 """Read cmdargs and write pager command to r-channel if enabled
466
474
467 If pager isn't enabled, this writes '\0' because channeledoutput
475 If pager isn't enabled, this writes '\0' because channeledoutput
468 does not allow to write empty data.
476 does not allow to write empty data.
469 """
477 """
470 args = self._readlist()
478 args = self._readlist()
471 try:
479 try:
472 cmd, _func, args, options, _cmdoptions = dispatch._parse(self.ui,
480 cmd, _func, args, options, _cmdoptions = dispatch._parse(self.ui,
473 args)
481 args)
474 except (error.Abort, error.AmbiguousCommand, error.CommandError,
482 except (error.Abort, error.AmbiguousCommand, error.CommandError,
475 error.UnknownCommand):
483 error.UnknownCommand):
476 cmd = None
484 cmd = None
477 options = {}
485 options = {}
478 if not cmd or 'pager' not in options:
486 if not cmd or 'pager' not in options:
479 self.cresult.write('\0')
487 self.cresult.write('\0')
480 return
488 return
481
489
482 pagercmd = _setuppagercmd(self.ui, options, cmd)
490 pagercmd = _setuppagercmd(self.ui, options, cmd)
483 if pagercmd:
491 if pagercmd:
484 self.cresult.write(pagercmd)
492 self.cresult.write(pagercmd)
485 else:
493 else:
486 self.cresult.write('\0')
494 self.cresult.write('\0')
487
495
488 def setenv(self):
496 def setenv(self):
489 """Clear and update os.environ
497 """Clear and update os.environ
490
498
491 Note that not all variables can make an effect on the running process.
499 Note that not all variables can make an effect on the running process.
492 """
500 """
493 l = self._readlist()
501 l = self._readlist()
494 try:
502 try:
495 newenv = dict(s.split('=', 1) for s in l)
503 newenv = dict(s.split('=', 1) for s in l)
496 except ValueError:
504 except ValueError:
497 raise ValueError('unexpected value in setenv request')
505 raise ValueError('unexpected value in setenv request')
498
506
499 diffkeys = set(k for k in set(os.environ.keys() + newenv.keys())
507 diffkeys = set(k for k in set(os.environ.keys() + newenv.keys())
500 if os.environ.get(k) != newenv.get(k))
508 if os.environ.get(k) != newenv.get(k))
501 _log('change env: %r\n' % sorted(diffkeys))
509 _log('change env: %r\n' % sorted(diffkeys))
502
510
503 os.environ.clear()
511 os.environ.clear()
504 os.environ.update(newenv)
512 os.environ.update(newenv)
505
513
506 if set(['HGPLAIN', 'HGPLAINEXCEPT']) & diffkeys:
514 if set(['HGPLAIN', 'HGPLAINEXCEPT']) & diffkeys:
507 # reload config so that ui.plain() takes effect
515 # reload config so that ui.plain() takes effect
508 self.ui = _renewui(self.ui)
516 self.ui = _renewui(self.ui)
509
517
510 _clearenvaliases(commands.table)
518 _clearenvaliases(commands.table)
511
519
512 capabilities = commandserver.server.capabilities.copy()
520 capabilities = commandserver.server.capabilities.copy()
513 capabilities.update({'attachio': attachio,
521 capabilities.update({'attachio': attachio,
514 'chdir': chdir,
522 'chdir': chdir,
515 'getpager': getpager,
523 'getpager': getpager,
516 'setenv': setenv,
524 'setenv': setenv,
517 'setumask': setumask})
525 'setumask': setumask})
518
526
519 # copied from mercurial/commandserver.py
527 # copied from mercurial/commandserver.py
520 class _requesthandler(SocketServer.StreamRequestHandler):
528 class _requesthandler(SocketServer.StreamRequestHandler):
521 def handle(self):
529 def handle(self):
522 # use a different process group from the master process, making this
530 # use a different process group from the master process, making this
523 # process pass kernel "is_current_pgrp_orphaned" check so signals like
531 # process pass kernel "is_current_pgrp_orphaned" check so signals like
524 # SIGTSTP, SIGTTIN, SIGTTOU are not ignored.
532 # SIGTSTP, SIGTTIN, SIGTTOU are not ignored.
525 os.setpgid(0, 0)
533 os.setpgid(0, 0)
526 ui = self.server.ui
534 ui = self.server.ui
527 repo = self.server.repo
535 repo = self.server.repo
528 sv = None
536 sv = None
529 try:
537 try:
530 sv = chgcmdserver(ui, repo, self.rfile, self.wfile, self.connection,
538 sv = chgcmdserver(ui, repo, self.rfile, self.wfile, self.connection,
531 self.server.hashstate, self.server.baseaddress)
539 self.server.hashstate, self.server.baseaddress)
532 try:
540 try:
533 sv.serve()
541 sv.serve()
534 # handle exceptions that may be raised by command server. most of
542 # handle exceptions that may be raised by command server. most of
535 # known exceptions are caught by dispatch.
543 # known exceptions are caught by dispatch.
536 except error.Abort as inst:
544 except error.Abort as inst:
537 ui.warn(_('abort: %s\n') % inst)
545 ui.warn(_('abort: %s\n') % inst)
538 except IOError as inst:
546 except IOError as inst:
539 if inst.errno != errno.EPIPE:
547 if inst.errno != errno.EPIPE:
540 raise
548 raise
541 except KeyboardInterrupt:
549 except KeyboardInterrupt:
542 pass
550 pass
543 finally:
551 finally:
544 sv.cleanup()
552 sv.cleanup()
545 except: # re-raises
553 except: # re-raises
546 # also write traceback to error channel. otherwise client cannot
554 # also write traceback to error channel. otherwise client cannot
547 # see it because it is written to server's stderr by default.
555 # see it because it is written to server's stderr by default.
548 if sv:
556 if sv:
549 cerr = sv.cerr
557 cerr = sv.cerr
550 else:
558 else:
551 cerr = commandserver.channeledoutput(self.wfile, 'e')
559 cerr = commandserver.channeledoutput(self.wfile, 'e')
552 traceback.print_exc(file=cerr)
560 traceback.print_exc(file=cerr)
553 raise
561 raise
554
562
555 def _tempaddress(address):
563 def _tempaddress(address):
556 return '%s.%d.tmp' % (address, os.getpid())
564 return '%s.%d.tmp' % (address, os.getpid())
557
565
558 def _hashaddress(address, hashstr):
566 def _hashaddress(address, hashstr):
559 return '%s-%s' % (address, hashstr)
567 return '%s-%s' % (address, hashstr)
560
568
561 class AutoExitMixIn: # use old-style to comply with SocketServer design
569 class AutoExitMixIn: # use old-style to comply with SocketServer design
562 lastactive = time.time()
570 lastactive = time.time()
563 idletimeout = 3600 # default 1 hour
571 idletimeout = 3600 # default 1 hour
564
572
565 def startautoexitthread(self):
573 def startautoexitthread(self):
566 # note: the auto-exit check here is cheap enough to not use a thread,
574 # note: the auto-exit check here is cheap enough to not use a thread,
567 # be done in serve_forever. however SocketServer is hook-unfriendly,
575 # be done in serve_forever. however SocketServer is hook-unfriendly,
568 # you simply cannot hook serve_forever without copying a lot of code.
576 # you simply cannot hook serve_forever without copying a lot of code.
569 # besides, serve_forever's docstring suggests using thread.
577 # besides, serve_forever's docstring suggests using thread.
570 thread = threading.Thread(target=self._autoexitloop)
578 thread = threading.Thread(target=self._autoexitloop)
571 thread.daemon = True
579 thread.daemon = True
572 thread.start()
580 thread.start()
573
581
574 def _autoexitloop(self, interval=1):
582 def _autoexitloop(self, interval=1):
575 while True:
583 while True:
576 time.sleep(interval)
584 time.sleep(interval)
577 if not self.issocketowner():
585 if not self.issocketowner():
578 _log('%s is not owned, exiting.\n' % self.server_address)
586 _log('%s is not owned, exiting.\n' % self.server_address)
579 break
587 break
580 if time.time() - self.lastactive > self.idletimeout:
588 if time.time() - self.lastactive > self.idletimeout:
581 _log('being idle too long. exiting.\n')
589 _log('being idle too long. exiting.\n')
582 break
590 break
583 self.shutdown()
591 self.shutdown()
584
592
585 def process_request(self, request, address):
593 def process_request(self, request, address):
586 self.lastactive = time.time()
594 self.lastactive = time.time()
587 return SocketServer.ForkingMixIn.process_request(
595 return SocketServer.ForkingMixIn.process_request(
588 self, request, address)
596 self, request, address)
589
597
590 def server_bind(self):
598 def server_bind(self):
591 # use a unique temp address so we can stat the file and do ownership
599 # use a unique temp address so we can stat the file and do ownership
592 # check later
600 # check later
593 tempaddress = _tempaddress(self.server_address)
601 tempaddress = _tempaddress(self.server_address)
594 self.socket.bind(tempaddress)
602 self.socket.bind(tempaddress)
595 self._socketstat = os.stat(tempaddress)
603 self._socketstat = os.stat(tempaddress)
596 # rename will replace the old socket file if exists atomically. the
604 # rename will replace the old socket file if exists atomically. the
597 # old server will detect ownership change and exit.
605 # old server will detect ownership change and exit.
598 util.rename(tempaddress, self.server_address)
606 util.rename(tempaddress, self.server_address)
599
607
600 def issocketowner(self):
608 def issocketowner(self):
601 try:
609 try:
602 stat = os.stat(self.server_address)
610 stat = os.stat(self.server_address)
603 return (stat.st_ino == self._socketstat.st_ino and
611 return (stat.st_ino == self._socketstat.st_ino and
604 stat.st_mtime == self._socketstat.st_mtime)
612 stat.st_mtime == self._socketstat.st_mtime)
605 except OSError:
613 except OSError:
606 return False
614 return False
607
615
608 def unlinksocketfile(self):
616 def unlinksocketfile(self):
609 if not self.issocketowner():
617 if not self.issocketowner():
610 return
618 return
611 # it is possible to have a race condition here that we may
619 # it is possible to have a race condition here that we may
612 # remove another server's socket file. but that's okay
620 # remove another server's socket file. but that's okay
613 # since that server will detect and exit automatically and
621 # since that server will detect and exit automatically and
614 # the client will start a new server on demand.
622 # the client will start a new server on demand.
615 try:
623 try:
616 os.unlink(self.server_address)
624 os.unlink(self.server_address)
617 except OSError as exc:
625 except OSError as exc:
618 if exc.errno != errno.ENOENT:
626 if exc.errno != errno.ENOENT:
619 raise
627 raise
620
628
621 class chgunixservice(commandserver.unixservice):
629 class chgunixservice(commandserver.unixservice):
622 def init(self):
630 def init(self):
623 self._inithashstate()
631 self._inithashstate()
624 class cls(AutoExitMixIn, SocketServer.ForkingMixIn,
632 class cls(AutoExitMixIn, SocketServer.ForkingMixIn,
625 SocketServer.UnixStreamServer):
633 SocketServer.UnixStreamServer):
626 ui = self.ui
634 ui = self.ui
627 repo = self.repo
635 repo = self.repo
628 hashstate = self.hashstate
636 hashstate = self.hashstate
629 baseaddress = self.baseaddress
637 baseaddress = self.baseaddress
630 self.server = cls(self.address, _requesthandler)
638 self.server = cls(self.address, _requesthandler)
631 self.server.idletimeout = self.ui.configint(
639 self.server.idletimeout = self.ui.configint(
632 'chgserver', 'idletimeout', self.server.idletimeout)
640 'chgserver', 'idletimeout', self.server.idletimeout)
633 self.server.startautoexitthread()
641 self.server.startautoexitthread()
634 self._createsymlink()
642 self._createsymlink()
635
643
636 def _inithashstate(self):
644 def _inithashstate(self):
637 self.baseaddress = self.address
645 self.baseaddress = self.address
638 if self.ui.configbool('chgserver', 'skiphash', False):
646 if self.ui.configbool('chgserver', 'skiphash', False):
639 self.hashstate = None
647 self.hashstate = None
640 return
648 return
641 self.hashstate = hashstate.fromui(self.ui)
649 self.hashstate = hashstate.fromui(self.ui)
642 self.address = _hashaddress(self.address, self.hashstate.confighash)
650 self.address = _hashaddress(self.address, self.hashstate.confighash)
643
651
644 def _createsymlink(self):
652 def _createsymlink(self):
645 if self.baseaddress == self.address:
653 if self.baseaddress == self.address:
646 return
654 return
647 tempaddress = _tempaddress(self.baseaddress)
655 tempaddress = _tempaddress(self.baseaddress)
648 os.symlink(os.path.basename(self.address), tempaddress)
656 os.symlink(os.path.basename(self.address), tempaddress)
649 util.rename(tempaddress, self.baseaddress)
657 util.rename(tempaddress, self.baseaddress)
650
658
651 def run(self):
659 def run(self):
652 try:
660 try:
653 self.server.serve_forever()
661 self.server.serve_forever()
654 finally:
662 finally:
655 self.server.unlinksocketfile()
663 self.server.unlinksocketfile()
656
664
657 def uisetup(ui):
665 def uisetup(ui):
658 commandserver._servicemap['chgunix'] = chgunixservice
666 commandserver._servicemap['chgunix'] = chgunixservice
659
667
660 # CHGINTERNALMARK is temporarily set by chg client to detect if chg will
668 # CHGINTERNALMARK is temporarily set by chg client to detect if chg will
661 # start another chg. drop it to avoid possible side effects.
669 # start another chg. drop it to avoid possible side effects.
662 if 'CHGINTERNALMARK' in os.environ:
670 if 'CHGINTERNALMARK' in os.environ:
663 del os.environ['CHGINTERNALMARK']
671 del os.environ['CHGINTERNALMARK']
General Comments 0
You need to be logged in to leave comments. Login now