Debian Codegraph @

contrib/chg/hgclient.c

raw
1 /*
2 * A command server client that uses Unix domain socket
3 *
4 * Copyright (c) 2011 Yuya Nishihara <[email protected]>
5 *
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.
8 */
9
10 #if defined(__sun) && !defined(_XOPEN_SOURCE)
11 /* msg_control is used */
12 #define _XOPEN_SOURCE 600
13 #endif
14
15 #include <arpa/inet.h> /* for ntohl(), htonl() */
16 #include <assert.h>
17 #include <ctype.h>
18 #include <errno.h>
19 #include <fcntl.h>
20 #include <signal.h>
21 #include <stdint.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <sys/socket.h>
26 #include <sys/stat.h>
27 #include <sys/un.h>
28 #include <unistd.h>
29
30 #include "hgclient.h"
31 #include "procutil.h"
32 #include "util.h"
33
34 #ifndef O_DIRECTORY
35 #define O_DIRECTORY O_RDONLY
36 #endif
37
38 enum {
39 CAP_GETENCODING = 0x0001,
40 CAP_RUNCOMMAND = 0x0002,
41 /* cHg extension: */
42 CAP_ATTACHIO = 0x0100,
43 CAP_CHDIR = 0x0200,
44 CAP_SETENV = 0x0800,
45 CAP_SETUMASK2 = 0x1000,
46 CAP_VALIDATE = 0x2000,
47 CAP_SETPROCNAME = 0x4000,
48 };
49
50 typedef struct {
51 const char *name;
52 unsigned int flag;
53 } cappair_t;
54
55 static const cappair_t captable[] = {
56 {"getencoding", CAP_GETENCODING},
57 {"runcommand", CAP_RUNCOMMAND},
58 {"attachio", CAP_ATTACHIO},
59 {"chdir", CAP_CHDIR},
60 {"setenv", CAP_SETENV},
61 {"setumask2", CAP_SETUMASK2},
62 {"validate", CAP_VALIDATE},
63 {"setprocname", CAP_SETPROCNAME},
64 {NULL, 0}, /* terminator */
65 };
66
67 typedef struct {
68 char ch;
69 char *data;
70 size_t maxdatasize;
71 size_t datasize;
72 } context_t;
73
74 struct hgclient_tag_ {
75 int sockfd;
76 pid_t pgid;
77 pid_t pid;
78 context_t ctx;
79 unsigned int capflags;
80 };
81
82 static const size_t defaultdatasize = 4096;
83
84 static void attachio(hgclient_t *hgc);
85
86 static void initcontext(context_t *ctx)
87 {
88 ctx->ch = '\0';
89 ctx->data = malloc(defaultdatasize);
90 ctx->maxdatasize = (ctx->data) ? defaultdatasize : 0;
91 ctx->datasize = 0;
92 debugmsg("initialize context buffer with size %zu", ctx->maxdatasize);
93 }
94
95 static void enlargecontext(context_t *ctx, size_t newsize)
96 {
97 if (newsize <= ctx->maxdatasize) {
98 return;
99 }
100
101 newsize = defaultdatasize *
102 ((newsize + defaultdatasize - 1) / defaultdatasize);
103 ctx->data = reallocx(ctx->data, newsize);
104 ctx->maxdatasize = newsize;
105 debugmsg("enlarge context buffer to %zu", ctx->maxdatasize);
106 }
107
108 static void freecontext(context_t *ctx)
109 {
110 debugmsg("free context buffer");
111 free(ctx->data);
112 ctx->data = NULL;
113 ctx->maxdatasize = 0;
114 ctx->datasize = 0;
115 }
116
117 /* Read channeled response from cmdserver */
118 static void readchannel(hgclient_t *hgc)
119 {
120 assert(hgc);
121
122 ssize_t rsize = recv(hgc->sockfd, &hgc->ctx.ch, sizeof(hgc->ctx.ch), 0);
123 if (rsize != sizeof(hgc->ctx.ch)) {
124 /* server would have exception and traceback would be printed */
125 debugmsg("failed to read channel");
126 exit(255);
127 }
128
129 uint32_t datasize_n;
130 rsize = recv(hgc->sockfd, &datasize_n, sizeof(datasize_n), 0);
131 if (rsize != sizeof(datasize_n)) {
132 abortmsg("failed to read data size");
133 }
134
135 /* datasize denotes the maximum size to write if input request */
136 hgc->ctx.datasize = ntohl(datasize_n);
137 enlargecontext(&hgc->ctx, hgc->ctx.datasize);
138
139 if (isupper(hgc->ctx.ch) && hgc->ctx.ch != 'S') {
140 return; /* assumes input request */
141 }
142
143 size_t cursize = 0;
144 while (cursize < hgc->ctx.datasize) {
145 rsize = recv(hgc->sockfd, hgc->ctx.data + cursize,
146 hgc->ctx.datasize - cursize, 0);
147 if (rsize < 1) {
148 abortmsg("failed to read data block");
149 }
150 cursize += rsize;
151 }
152 }
153
154 static void sendall(int sockfd, const void *data, size_t datasize)
155 {
156 const char *p = data;
157 const char *const endp = p + datasize;
158 while (p < endp) {
159 ssize_t r = send(sockfd, p, endp - p, 0);
160 if (r < 0) {
161 abortmsgerrno("cannot communicate");
162 }
163 p += r;
164 }
165 }
166
167 /* Write lengh-data block to cmdserver */
168 static void writeblock(const hgclient_t *hgc)
169 {
170 assert(hgc);
171
172 const uint32_t datasize_n = htonl(hgc->ctx.datasize);
173 sendall(hgc->sockfd, &datasize_n, sizeof(datasize_n));
174
175 sendall(hgc->sockfd, hgc->ctx.data, hgc->ctx.datasize);
176 }
177
178 static void writeblockrequest(const hgclient_t *hgc, const char *chcmd)
179 {
180 debugmsg("request %s, block size %zu", chcmd, hgc->ctx.datasize);
181
182 char buf[strlen(chcmd) + 1];
183 memcpy(buf, chcmd, sizeof(buf) - 1);
184 buf[sizeof(buf) - 1] = '\n';
185 sendall(hgc->sockfd, buf, sizeof(buf));
186
187 writeblock(hgc);
188 }
189
190 /* Build '\0'-separated list of args. argsize < 0 denotes that args are
191 * terminated by NULL. */
192 static void packcmdargs(context_t *ctx, const char *const args[],
193 ssize_t argsize)
194 {
195 ctx->datasize = 0;
196 const char *const *const end = (argsize >= 0) ? args + argsize : NULL;
197 for (const char *const *it = args; it != end && *it; ++it) {
198 const size_t n = strlen(*it) + 1; /* include '\0' */
199 enlargecontext(ctx, ctx->datasize + n);
200 memcpy(ctx->data + ctx->datasize, *it, n);
201 ctx->datasize += n;
202 }
203
204 if (ctx->datasize > 0) {
205 --ctx->datasize; /* strip last '\0' */
206 }
207 }
208
209 /* Extract '\0'-separated list of args to new buffer, terminated by NULL */
210 static const char **unpackcmdargsnul(const context_t *ctx)
211 {
212 const char **args = NULL;
213 size_t nargs = 0, maxnargs = 0;
214 const char *s = ctx->data;
215 const char *e = ctx->data + ctx->datasize;
216 for (;;) {
217 if (nargs + 1 >= maxnargs) { /* including last NULL */
218 maxnargs += 256;
219 args = reallocx(args, maxnargs * sizeof(args[0]));
220 }
221 args[nargs] = s;
222 nargs++;
223 s = memchr(s, '\0', e - s);
224 if (!s) {
225 break;
226 }
227 s++;
228 }
229 args[nargs] = NULL;
230 return args;
231 }
232
233 static void handlereadrequest(hgclient_t *hgc)
234 {
235 context_t *ctx = &hgc->ctx;
236 size_t r = fread(ctx->data, sizeof(ctx->data[0]), ctx->datasize, stdin);
237 ctx->datasize = r;
238 writeblock(hgc);
239 }
240
241 /* Read single-line */
242 static void handlereadlinerequest(hgclient_t *hgc)
243 {
244 context_t *ctx = &hgc->ctx;
245 if (!fgets(ctx->data, ctx->datasize, stdin)) {
246 ctx->data[0] = '\0';
247 }
248 ctx->datasize = strlen(ctx->data);
249 writeblock(hgc);
250 }
251
252 /* Execute the requested command and write exit code */
253 static void handlesystemrequest(hgclient_t *hgc)
254 {
255 context_t *ctx = &hgc->ctx;
256 enlargecontext(ctx, ctx->datasize + 1);
257 ctx->data[ctx->datasize] = '\0'; /* terminate last string */
258
259 const char **args = unpackcmdargsnul(ctx);
260 if (!args[0] || !args[1] || !args[2]) {
261 abortmsg("missing type or command or cwd in system request");
262 }
263 if (strcmp(args[0], "system") == 0) {
264 debugmsg("run '%s' at '%s'", args[1], args[2]);
265 int32_t r = runshellcmd(args[1], args + 3, args[2]);
266 free(args);
267
268 uint32_t r_n = htonl(r);
269 memcpy(ctx->data, &r_n, sizeof(r_n));
270 ctx->datasize = sizeof(r_n);
271 writeblock(hgc);
272 } else if (strcmp(args[0], "pager") == 0) {
273 setuppager(args[1], args + 3);
274 if (hgc->capflags & CAP_ATTACHIO) {
275 attachio(hgc);
276 }
277 /* unblock the server */
278 static const char emptycmd[] = "\n";
279 sendall(hgc->sockfd, emptycmd, sizeof(emptycmd) - 1);
280 } else {
281 abortmsg("unknown type in system request: %s", args[0]);
282 }
283 }
284
285 /* Read response of command execution until receiving 'r'-esult */
286 static void handleresponse(hgclient_t *hgc)
287 {
288 for (;;) {
289 readchannel(hgc);
290 context_t *ctx = &hgc->ctx;
291 debugmsg("response read from channel %c, size %zu", ctx->ch,
292 ctx->datasize);
293 switch (ctx->ch) {
294 case 'o':
295 fwrite(ctx->data, sizeof(ctx->data[0]), ctx->datasize,
296 stdout);
297 break;
298 case 'e':
299 fwrite(ctx->data, sizeof(ctx->data[0]), ctx->datasize,
300 stderr);
301 break;
302 case 'd':
303 /* assumes last char is '\n' */
304 ctx->data[ctx->datasize - 1] = '\0';
305 debugmsg("server: %s", ctx->data);
306 break;
307 case 'r':
308 return;
309 case 'I':
310 handlereadrequest(hgc);
311 break;
312 case 'L':
313 handlereadlinerequest(hgc);
314 break;
315 case 'S':
316 handlesystemrequest(hgc);
317 break;
318 default:
319 if (isupper(ctx->ch)) {
320 abortmsg("cannot handle response (ch = %c)",
321 ctx->ch);
322 }
323 }
324 }
325 }
326
327 static unsigned int parsecapabilities(const char *s, const char *e)
328 {
329 unsigned int flags = 0;
330 while (s < e) {
331 const char *t = strchr(s, ' ');
332 if (!t || t > e) {
333 t = e;
334 }
335 const cappair_t *cap;
336 for (cap = captable; cap->flag; ++cap) {
337 size_t n = t - s;
338 if (strncmp(s, cap->name, n) == 0 &&
339 strlen(cap->name) == n) {
340 flags |= cap->flag;
341 break;
342 }
343 }
344 s = t + 1;
345 }
346 return flags;
347 }
348
349 static void readhello(hgclient_t *hgc)
350 {
351 readchannel(hgc);
352 context_t *ctx = &hgc->ctx;
353 if (ctx->ch != 'o') {
354 char ch = ctx->ch;
355 if (ch == 'e') {
356 /* write early error and will exit */
357 fwrite(ctx->data, sizeof(ctx->data[0]), ctx->datasize,
358 stderr);
359 handleresponse(hgc);
360 }
361 abortmsg("unexpected channel of hello message (ch = %c)", ch);
362 }
363 enlargecontext(ctx, ctx->datasize + 1);
364 ctx->data[ctx->datasize] = '\0';
365 debugmsg("hello received: %s (size = %zu)", ctx->data, ctx->datasize);
366
367 const char *s = ctx->data;
368 const char *const dataend = ctx->data + ctx->datasize;
369 while (s < dataend) {
370 const char *t = strchr(s, ':');
371 if (!t || t[1] != ' ') {
372 break;
373 }
374 const char *u = strchr(t + 2, '\n');
375 if (!u) {
376 u = dataend;
377 }
378 if (strncmp(s, "capabilities:", t - s + 1) == 0) {
379 hgc->capflags = parsecapabilities(t + 2, u);
380 } else if (strncmp(s, "pgid:", t - s + 1) == 0) {
381 hgc->pgid = strtol(t + 2, NULL, 10);
382 } else if (strncmp(s, "pid:", t - s + 1) == 0) {
383 hgc->pid = strtol(t + 2, NULL, 10);
384 }
385 s = u + 1;
386 }
387 debugmsg("capflags=0x%04x, pid=%d", hgc->capflags, hgc->pid);
388 }
389
390 static void updateprocname(hgclient_t *hgc)
391 {
392 int r = snprintf(hgc->ctx.data, hgc->ctx.maxdatasize, "chg[worker/%d]",
393 (int)getpid());
394 if (r < 0 || (size_t)r >= hgc->ctx.maxdatasize) {
395 abortmsg("insufficient buffer to write procname (r = %d)", r);
396 }
397 hgc->ctx.datasize = (size_t)r;
398 writeblockrequest(hgc, "setprocname");
399 }
400
401 static void attachio(hgclient_t *hgc)
402 {
403 debugmsg("request attachio");
404 static const char chcmd[] = "attachio\n";
405 sendall(hgc->sockfd, chcmd, sizeof(chcmd) - 1);
406 readchannel(hgc);
407 context_t *ctx = &hgc->ctx;
408 if (ctx->ch != 'I') {
409 abortmsg("unexpected response for attachio (ch = %c)", ctx->ch);
410 }
411
412 static const int fds[3] = {STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO};
413 struct msghdr msgh;
414 memset(&msgh, 0, sizeof(msgh));
415 struct iovec iov = {ctx->data, ctx->datasize}; /* dummy payload */
416 msgh.msg_iov = &iov;
417 msgh.msg_iovlen = 1;
418 char fdbuf[CMSG_SPACE(sizeof(fds))];
419 msgh.msg_control = fdbuf;
420 msgh.msg_controllen = sizeof(fdbuf);
421 struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msgh);
422 cmsg->cmsg_level = SOL_SOCKET;
423 cmsg->cmsg_type = SCM_RIGHTS;
424 cmsg->cmsg_len = CMSG_LEN(sizeof(fds));
425 memcpy(CMSG_DATA(cmsg), fds, sizeof(fds));
426 msgh.msg_controllen = cmsg->cmsg_len;
427 ssize_t r = sendmsg(hgc->sockfd, &msgh, 0);
428 if (r < 0) {
429 abortmsgerrno("sendmsg failed");
430 }
431
432 handleresponse(hgc);
433 int32_t n;
434 if (ctx->datasize != sizeof(n)) {
435 abortmsg("unexpected size of attachio result");
436 }
437 memcpy(&n, ctx->data, sizeof(n));
438 n = ntohl(n);
439 if (n != sizeof(fds) / sizeof(fds[0])) {
440 abortmsg("failed to send fds (n = %d)", n);
441 }
442 }
443
444 static void chdirtocwd(hgclient_t *hgc)
445 {
446 if (!getcwd(hgc->ctx.data, hgc->ctx.maxdatasize)) {
447 abortmsgerrno("failed to getcwd");
448 }
449 hgc->ctx.datasize = strlen(hgc->ctx.data);
450 writeblockrequest(hgc, "chdir");
451 }
452
453 static void forwardumask(hgclient_t *hgc)
454 {
455 mode_t mask = umask(0);
456 umask(mask);
457
458 uint32_t data = htonl(mask);
459 enlargecontext(&hgc->ctx, sizeof(data));
460 memcpy(hgc->ctx.data, &data, sizeof(data));
461 hgc->ctx.datasize = sizeof(data);
462 writeblockrequest(hgc, "setumask2");
463 }
464
465 /*!
466 * Open connection to per-user cmdserver
467 *
468 * If no background server running, returns NULL.
469 */
470 hgclient_t *hgc_open(const char *sockname)
471 {
472 int fd = socket(AF_UNIX, SOCK_STREAM, 0);
473 if (fd < 0) {
474 abortmsgerrno("cannot create socket");
475 }
476
477 /* don't keep fd on fork(), so that it can be closed when the parent
478 * process get terminated. */
479 fsetcloexec(fd);
480
481 struct sockaddr_un addr;
482 addr.sun_family = AF_UNIX;
483
484 /* use chdir to workaround small sizeof(sun_path) */
485 int bakfd = -1;
486 const char *basename = sockname;
487 {
488 const char *split = strrchr(sockname, '/');
489 if (split && split != sockname) {
490 if (split[1] == '\0') {
491 abortmsg("sockname cannot end with a slash");
492 }
493 size_t len = split - sockname;
494 char sockdir[len + 1];
495 memcpy(sockdir, sockname, len);
496 sockdir[len] = '\0';
497
498 bakfd = open(".", O_DIRECTORY);
499 if (bakfd == -1) {
500 abortmsgerrno("cannot open cwd");
501 }
502
503 int r = chdir(sockdir);
504 if (r != 0) {
505 abortmsgerrno("cannot chdir %s", sockdir);
506 }
507
508 basename = split + 1;
509 }
510 }
511 if (strlen(basename) >= sizeof(addr.sun_path)) {
512 abortmsg("sockname is too long: %s", basename);
513 }
514 strncpy(addr.sun_path, basename, sizeof(addr.sun_path));
515 addr.sun_path[sizeof(addr.sun_path) - 1] = '\0';
516
517 /* real connect */
518 int r = connect(fd, (struct sockaddr *)&addr, sizeof(addr));
519 if (r < 0) {
520 if (errno != ENOENT && errno != ECONNREFUSED) {
521 abortmsgerrno("cannot connect to %s", sockname);
522 }
523 }
524 if (bakfd != -1) {
525 fchdirx(bakfd);
526 close(bakfd);
527 }
528 if (r < 0) {
529 close(fd);
530 return NULL;
531 }
532 debugmsg("connected to %s", addr.sun_path);
533
534 hgclient_t *hgc = mallocx(sizeof(hgclient_t));
535 memset(hgc, 0, sizeof(*hgc));
536 hgc->sockfd = fd;
537 initcontext(&hgc->ctx);
538
539 readhello(hgc);
540 if (!(hgc->capflags & CAP_RUNCOMMAND)) {
541 abortmsg("insufficient capability: runcommand");
542 }
543 if (hgc->capflags & CAP_SETPROCNAME) {
544 updateprocname(hgc);
545 }
546 if (hgc->capflags & CAP_ATTACHIO) {
547 attachio(hgc);
548 }
549 if (hgc->capflags & CAP_CHDIR) {
550 chdirtocwd(hgc);
551 }
552 if (hgc->capflags & CAP_SETUMASK2) {
553 forwardumask(hgc);
554 }
555
556 return hgc;
557 }
558
559 /*!
560 * Close connection and free allocated memory
561 */
562 void hgc_close(hgclient_t *hgc)
563 {
564 assert(hgc);
565 freecontext(&hgc->ctx);
566 close(hgc->sockfd);
567 free(hgc);
568 }
569
570 pid_t hgc_peerpgid(const hgclient_t *hgc)
571 {
572 assert(hgc);
573 return hgc->pgid;
574 }
575
576 pid_t hgc_peerpid(const hgclient_t *hgc)
577 {
578 assert(hgc);
579 return hgc->pid;
580 }
581
582 /*!
583 * Send command line arguments to let the server load the repo config and check
584 * whether it can process our request directly or not.
585 * Make sure hgc_setenv is called before calling this.
586 *
587 * @return - NULL, the server believes it can handle our request, or does not
588 * support "validate" command.
589 * - a list of strings, the server probably cannot handle our request
590 * and it sent instructions telling us what to do next. See
591 * chgserver.py for possible instruction formats.
592 * the list should be freed by the caller.
593 * the last string is guaranteed to be NULL.
594 */
595 const char **hgc_validate(hgclient_t *hgc, const char *const args[],
596 size_t argsize)
597 {
598 assert(hgc);
599 if (!(hgc->capflags & CAP_VALIDATE)) {
600 return NULL;
601 }
602
603 packcmdargs(&hgc->ctx, args, argsize);
604 writeblockrequest(hgc, "validate");
605 handleresponse(hgc);
606
607 /* the server returns '\0' if it can handle our request */
608 if (hgc->ctx.datasize <= 1) {
609 return NULL;
610 }
611
612 /* make sure the buffer is '\0' terminated */
613 enlargecontext(&hgc->ctx, hgc->ctx.datasize + 1);
614 hgc->ctx.data[hgc->ctx.datasize] = '\0';
615 return unpackcmdargsnul(&hgc->ctx);
616 }
617
618 /*!
619 * Execute the specified Mercurial command
620 *
621 * @return result code
622 */
623 int hgc_runcommand(hgclient_t *hgc, const char *const args[], size_t argsize)
624 {
625 assert(hgc);
626
627 packcmdargs(&hgc->ctx, args, argsize);
628 writeblockrequest(hgc, "runcommand");
629 handleresponse(hgc);
630
631 int32_t exitcode_n;
632 if (hgc->ctx.datasize != sizeof(exitcode_n)) {
633 abortmsg("unexpected size of exitcode");
634 }
635 memcpy(&exitcode_n, hgc->ctx.data, sizeof(exitcode_n));
636 return ntohl(exitcode_n);
637 }
638
639 /*!
640 * (Re-)send client's stdio channels so that the server can access to tty
641 */
642 void hgc_attachio(hgclient_t *hgc)
643 {
644 assert(hgc);
645 if (!(hgc->capflags & CAP_ATTACHIO)) {
646 return;
647 }
648 attachio(hgc);
649 }
650
651 /*!
652 * Update server's environment variables
653 *
654 * @param envp list of environment variables in "NAME=VALUE" format,
655 * terminated by NULL.
656 */
657 void hgc_setenv(hgclient_t *hgc, const char *const envp[])
658 {
659 assert(hgc && envp);
660 if (!(hgc->capflags & CAP_SETENV)) {
661 return;
662 }
663 packcmdargs(&hgc->ctx, envp, /*argsize*/ -1);
664 writeblockrequest(hgc, "setenv");
665 }