##// END OF EJS Templates
chg: extract the logic of setting FD_CLOEXEC to a utility function...
Jun Wu -
r28855:f5764e17 default
parent child Browse files
Show More
@@ -1,580 +1,576
1 1 /*
2 2 * A command server client that uses Unix domain socket
3 3 *
4 4 * Copyright (c) 2011 Yuya Nishihara <yuya@tcha.org>
5 5 *
6 6 * This software may be used and distributed according to the terms of the
7 7 * GNU General Public License version 2 or any later version.
8 8 */
9 9
10 10 #include <arpa/inet.h> /* for ntohl(), htonl() */
11 11 #include <assert.h>
12 12 #include <ctype.h>
13 13 #include <errno.h>
14 14 #include <fcntl.h>
15 15 #include <signal.h>
16 16 #include <stdint.h>
17 17 #include <stdio.h>
18 18 #include <stdlib.h>
19 19 #include <string.h>
20 20 #include <sys/socket.h>
21 21 #include <sys/stat.h>
22 22 #include <sys/un.h>
23 23 #include <unistd.h>
24 24
25 25 #include "hgclient.h"
26 26 #include "util.h"
27 27
28 28 enum {
29 29 CAP_GETENCODING = 0x0001,
30 30 CAP_RUNCOMMAND = 0x0002,
31 31 /* cHg extension: */
32 32 CAP_ATTACHIO = 0x0100,
33 33 CAP_CHDIR = 0x0200,
34 34 CAP_GETPAGER = 0x0400,
35 35 CAP_SETENV = 0x0800,
36 36 CAP_SETUMASK = 0x1000,
37 37 CAP_VALIDATE = 0x2000,
38 38 };
39 39
40 40 typedef struct {
41 41 const char *name;
42 42 unsigned int flag;
43 43 } cappair_t;
44 44
45 45 static const cappair_t captable[] = {
46 46 {"getencoding", CAP_GETENCODING},
47 47 {"runcommand", CAP_RUNCOMMAND},
48 48 {"attachio", CAP_ATTACHIO},
49 49 {"chdir", CAP_CHDIR},
50 50 {"getpager", CAP_GETPAGER},
51 51 {"setenv", CAP_SETENV},
52 52 {"setumask", CAP_SETUMASK},
53 53 {"validate", CAP_VALIDATE},
54 54 {NULL, 0}, /* terminator */
55 55 };
56 56
57 57 typedef struct {
58 58 char ch;
59 59 char *data;
60 60 size_t maxdatasize;
61 61 size_t datasize;
62 62 } context_t;
63 63
64 64 struct hgclient_tag_ {
65 65 int sockfd;
66 66 pid_t pid;
67 67 context_t ctx;
68 68 unsigned int capflags;
69 69 };
70 70
71 71 static const size_t defaultdatasize = 4096;
72 72
73 73 static void initcontext(context_t *ctx)
74 74 {
75 75 ctx->ch = '\0';
76 76 ctx->data = malloc(defaultdatasize);
77 77 ctx->maxdatasize = (ctx->data) ? defaultdatasize : 0;
78 78 ctx->datasize = 0;
79 79 debugmsg("initialize context buffer with size %zu", ctx->maxdatasize);
80 80 }
81 81
82 82 static void enlargecontext(context_t *ctx, size_t newsize)
83 83 {
84 84 if (newsize <= ctx->maxdatasize)
85 85 return;
86 86
87 87 newsize = defaultdatasize
88 88 * ((newsize + defaultdatasize - 1) / defaultdatasize);
89 89 ctx->data = reallocx(ctx->data, newsize);
90 90 ctx->maxdatasize = newsize;
91 91 debugmsg("enlarge context buffer to %zu", ctx->maxdatasize);
92 92 }
93 93
94 94 static void freecontext(context_t *ctx)
95 95 {
96 96 debugmsg("free context buffer");
97 97 free(ctx->data);
98 98 ctx->data = NULL;
99 99 ctx->maxdatasize = 0;
100 100 ctx->datasize = 0;
101 101 }
102 102
103 103 /* Read channeled response from cmdserver */
104 104 static void readchannel(hgclient_t *hgc)
105 105 {
106 106 assert(hgc);
107 107
108 108 ssize_t rsize = recv(hgc->sockfd, &hgc->ctx.ch, sizeof(hgc->ctx.ch), 0);
109 109 if (rsize != sizeof(hgc->ctx.ch)) {
110 110 /* server would have exception and traceback would be printed */
111 111 debugmsg("failed to read channel");
112 112 exit(255);
113 113 }
114 114
115 115 uint32_t datasize_n;
116 116 rsize = recv(hgc->sockfd, &datasize_n, sizeof(datasize_n), 0);
117 117 if (rsize != sizeof(datasize_n))
118 118 abortmsg("failed to read data size");
119 119
120 120 /* datasize denotes the maximum size to write if input request */
121 121 hgc->ctx.datasize = ntohl(datasize_n);
122 122 enlargecontext(&hgc->ctx, hgc->ctx.datasize);
123 123
124 124 if (isupper(hgc->ctx.ch) && hgc->ctx.ch != 'S')
125 125 return; /* assumes input request */
126 126
127 127 size_t cursize = 0;
128 128 while (cursize < hgc->ctx.datasize) {
129 129 rsize = recv(hgc->sockfd, hgc->ctx.data + cursize,
130 130 hgc->ctx.datasize - cursize, 0);
131 131 if (rsize < 0)
132 132 abortmsg("failed to read data block");
133 133 cursize += rsize;
134 134 }
135 135 }
136 136
137 137 static void sendall(int sockfd, const void *data, size_t datasize)
138 138 {
139 139 const char *p = data;
140 140 const char *const endp = p + datasize;
141 141 while (p < endp) {
142 142 ssize_t r = send(sockfd, p, endp - p, 0);
143 143 if (r < 0)
144 144 abortmsgerrno("cannot communicate");
145 145 p += r;
146 146 }
147 147 }
148 148
149 149 /* Write lengh-data block to cmdserver */
150 150 static void writeblock(const hgclient_t *hgc)
151 151 {
152 152 assert(hgc);
153 153
154 154 const uint32_t datasize_n = htonl(hgc->ctx.datasize);
155 155 sendall(hgc->sockfd, &datasize_n, sizeof(datasize_n));
156 156
157 157 sendall(hgc->sockfd, hgc->ctx.data, hgc->ctx.datasize);
158 158 }
159 159
160 160 static void writeblockrequest(const hgclient_t *hgc, const char *chcmd)
161 161 {
162 162 debugmsg("request %s, block size %zu", chcmd, hgc->ctx.datasize);
163 163
164 164 char buf[strlen(chcmd) + 1];
165 165 memcpy(buf, chcmd, sizeof(buf) - 1);
166 166 buf[sizeof(buf) - 1] = '\n';
167 167 sendall(hgc->sockfd, buf, sizeof(buf));
168 168
169 169 writeblock(hgc);
170 170 }
171 171
172 172 /* Build '\0'-separated list of args. argsize < 0 denotes that args are
173 173 * terminated by NULL. */
174 174 static void packcmdargs(context_t *ctx, const char *const args[],
175 175 ssize_t argsize)
176 176 {
177 177 ctx->datasize = 0;
178 178 const char *const *const end = (argsize >= 0) ? args + argsize : NULL;
179 179 for (const char *const *it = args; it != end && *it; ++it) {
180 180 const size_t n = strlen(*it) + 1; /* include '\0' */
181 181 enlargecontext(ctx, ctx->datasize + n);
182 182 memcpy(ctx->data + ctx->datasize, *it, n);
183 183 ctx->datasize += n;
184 184 }
185 185
186 186 if (ctx->datasize > 0)
187 187 --ctx->datasize; /* strip last '\0' */
188 188 }
189 189
190 190 /* Extract '\0'-separated list of args to new buffer, terminated by NULL */
191 191 static const char **unpackcmdargsnul(const context_t *ctx)
192 192 {
193 193 const char **args = NULL;
194 194 size_t nargs = 0, maxnargs = 0;
195 195 const char *s = ctx->data;
196 196 const char *e = ctx->data + ctx->datasize;
197 197 for (;;) {
198 198 if (nargs + 1 >= maxnargs) { /* including last NULL */
199 199 maxnargs += 256;
200 200 args = reallocx(args, maxnargs * sizeof(args[0]));
201 201 }
202 202 args[nargs] = s;
203 203 nargs++;
204 204 s = memchr(s, '\0', e - s);
205 205 if (!s)
206 206 break;
207 207 s++;
208 208 }
209 209 args[nargs] = NULL;
210 210 return args;
211 211 }
212 212
213 213 static void handlereadrequest(hgclient_t *hgc)
214 214 {
215 215 context_t *ctx = &hgc->ctx;
216 216 size_t r = fread(ctx->data, sizeof(ctx->data[0]), ctx->datasize, stdin);
217 217 ctx->datasize = r;
218 218 writeblock(hgc);
219 219 }
220 220
221 221 /* Read single-line */
222 222 static void handlereadlinerequest(hgclient_t *hgc)
223 223 {
224 224 context_t *ctx = &hgc->ctx;
225 225 if (!fgets(ctx->data, ctx->datasize, stdin))
226 226 ctx->data[0] = '\0';
227 227 ctx->datasize = strlen(ctx->data);
228 228 writeblock(hgc);
229 229 }
230 230
231 231 /* Execute the requested command and write exit code */
232 232 static void handlesystemrequest(hgclient_t *hgc)
233 233 {
234 234 context_t *ctx = &hgc->ctx;
235 235 enlargecontext(ctx, ctx->datasize + 1);
236 236 ctx->data[ctx->datasize] = '\0'; /* terminate last string */
237 237
238 238 const char **args = unpackcmdargsnul(ctx);
239 239 if (!args[0] || !args[1])
240 240 abortmsg("missing command or cwd in system request");
241 241 debugmsg("run '%s' at '%s'", args[0], args[1]);
242 242 int32_t r = runshellcmd(args[0], args + 2, args[1]);
243 243 free(args);
244 244
245 245 uint32_t r_n = htonl(r);
246 246 memcpy(ctx->data, &r_n, sizeof(r_n));
247 247 ctx->datasize = sizeof(r_n);
248 248 writeblock(hgc);
249 249 }
250 250
251 251 /* Read response of command execution until receiving 'r'-esult */
252 252 static void handleresponse(hgclient_t *hgc)
253 253 {
254 254 for (;;) {
255 255 readchannel(hgc);
256 256 context_t *ctx = &hgc->ctx;
257 257 debugmsg("response read from channel %c, size %zu",
258 258 ctx->ch, ctx->datasize);
259 259 switch (ctx->ch) {
260 260 case 'o':
261 261 fwrite(ctx->data, sizeof(ctx->data[0]), ctx->datasize,
262 262 stdout);
263 263 break;
264 264 case 'e':
265 265 fwrite(ctx->data, sizeof(ctx->data[0]), ctx->datasize,
266 266 stderr);
267 267 break;
268 268 case 'd':
269 269 /* assumes last char is '\n' */
270 270 ctx->data[ctx->datasize - 1] = '\0';
271 271 debugmsg("server: %s", ctx->data);
272 272 break;
273 273 case 'r':
274 274 return;
275 275 case 'I':
276 276 handlereadrequest(hgc);
277 277 break;
278 278 case 'L':
279 279 handlereadlinerequest(hgc);
280 280 break;
281 281 case 'S':
282 282 handlesystemrequest(hgc);
283 283 break;
284 284 default:
285 285 if (isupper(ctx->ch))
286 286 abortmsg("cannot handle response (ch = %c)",
287 287 ctx->ch);
288 288 }
289 289 }
290 290 }
291 291
292 292 static unsigned int parsecapabilities(const char *s, const char *e)
293 293 {
294 294 unsigned int flags = 0;
295 295 while (s < e) {
296 296 const char *t = strchr(s, ' ');
297 297 if (!t || t > e)
298 298 t = e;
299 299 const cappair_t *cap;
300 300 for (cap = captable; cap->flag; ++cap) {
301 301 size_t n = t - s;
302 302 if (strncmp(s, cap->name, n) == 0 &&
303 303 strlen(cap->name) == n) {
304 304 flags |= cap->flag;
305 305 break;
306 306 }
307 307 }
308 308 s = t + 1;
309 309 }
310 310 return flags;
311 311 }
312 312
313 313 static void readhello(hgclient_t *hgc)
314 314 {
315 315 readchannel(hgc);
316 316 context_t *ctx = &hgc->ctx;
317 317 if (ctx->ch != 'o') {
318 318 char ch = ctx->ch;
319 319 if (ch == 'e') {
320 320 /* write early error and will exit */
321 321 fwrite(ctx->data, sizeof(ctx->data[0]), ctx->datasize,
322 322 stderr);
323 323 handleresponse(hgc);
324 324 }
325 325 abortmsg("unexpected channel of hello message (ch = %c)", ch);
326 326 }
327 327 enlargecontext(ctx, ctx->datasize + 1);
328 328 ctx->data[ctx->datasize] = '\0';
329 329 debugmsg("hello received: %s (size = %zu)", ctx->data, ctx->datasize);
330 330
331 331 const char *s = ctx->data;
332 332 const char *const dataend = ctx->data + ctx->datasize;
333 333 while (s < dataend) {
334 334 const char *t = strchr(s, ':');
335 335 if (!t || t[1] != ' ')
336 336 break;
337 337 const char *u = strchr(t + 2, '\n');
338 338 if (!u)
339 339 u = dataend;
340 340 if (strncmp(s, "capabilities:", t - s + 1) == 0) {
341 341 hgc->capflags = parsecapabilities(t + 2, u);
342 342 } else if (strncmp(s, "pid:", t - s + 1) == 0) {
343 343 hgc->pid = strtol(t + 2, NULL, 10);
344 344 }
345 345 s = u + 1;
346 346 }
347 347 debugmsg("capflags=0x%04x, pid=%d", hgc->capflags, hgc->pid);
348 348 }
349 349
350 350 static void attachio(hgclient_t *hgc)
351 351 {
352 352 debugmsg("request attachio");
353 353 static const char chcmd[] = "attachio\n";
354 354 sendall(hgc->sockfd, chcmd, sizeof(chcmd) - 1);
355 355 readchannel(hgc);
356 356 context_t *ctx = &hgc->ctx;
357 357 if (ctx->ch != 'I')
358 358 abortmsg("unexpected response for attachio (ch = %c)", ctx->ch);
359 359
360 360 static const int fds[3] = {STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO};
361 361 struct msghdr msgh;
362 362 memset(&msgh, 0, sizeof(msgh));
363 363 struct iovec iov = {ctx->data, ctx->datasize}; /* dummy payload */
364 364 msgh.msg_iov = &iov;
365 365 msgh.msg_iovlen = 1;
366 366 char fdbuf[CMSG_SPACE(sizeof(fds))];
367 367 msgh.msg_control = fdbuf;
368 368 msgh.msg_controllen = sizeof(fdbuf);
369 369 struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msgh);
370 370 cmsg->cmsg_level = SOL_SOCKET;
371 371 cmsg->cmsg_type = SCM_RIGHTS;
372 372 cmsg->cmsg_len = CMSG_LEN(sizeof(fds));
373 373 memcpy(CMSG_DATA(cmsg), fds, sizeof(fds));
374 374 msgh.msg_controllen = cmsg->cmsg_len;
375 375 ssize_t r = sendmsg(hgc->sockfd, &msgh, 0);
376 376 if (r < 0)
377 377 abortmsgerrno("sendmsg failed");
378 378
379 379 handleresponse(hgc);
380 380 int32_t n;
381 381 if (ctx->datasize != sizeof(n))
382 382 abortmsg("unexpected size of attachio result");
383 383 memcpy(&n, ctx->data, sizeof(n));
384 384 n = ntohl(n);
385 385 if (n != sizeof(fds) / sizeof(fds[0]))
386 386 abortmsg("failed to send fds (n = %d)", n);
387 387 }
388 388
389 389 static void chdirtocwd(hgclient_t *hgc)
390 390 {
391 391 if (!getcwd(hgc->ctx.data, hgc->ctx.maxdatasize))
392 392 abortmsgerrno("failed to getcwd");
393 393 hgc->ctx.datasize = strlen(hgc->ctx.data);
394 394 writeblockrequest(hgc, "chdir");
395 395 }
396 396
397 397 static void forwardumask(hgclient_t *hgc)
398 398 {
399 399 mode_t mask = umask(0);
400 400 umask(mask);
401 401
402 402 static const char command[] = "setumask\n";
403 403 sendall(hgc->sockfd, command, sizeof(command) - 1);
404 404 uint32_t data = htonl(mask);
405 405 sendall(hgc->sockfd, &data, sizeof(data));
406 406 }
407 407
408 408 /*!
409 409 * Open connection to per-user cmdserver
410 410 *
411 411 * If no background server running, returns NULL.
412 412 */
413 413 hgclient_t *hgc_open(const char *sockname)
414 414 {
415 415 int fd = socket(AF_UNIX, SOCK_STREAM, 0);
416 416 if (fd < 0)
417 417 abortmsgerrno("cannot create socket");
418 418
419 419 /* don't keep fd on fork(), so that it can be closed when the parent
420 420 * process get terminated. */
421 int flags = fcntl(fd, F_GETFD);
422 if (flags < 0)
423 abortmsgerrno("cannot get flags of socket");
424 if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) < 0)
425 abortmsgerrno("cannot set flags of socket");
421 fsetcloexec(fd);
426 422
427 423 struct sockaddr_un addr;
428 424 addr.sun_family = AF_UNIX;
429 425 strncpy(addr.sun_path, sockname, sizeof(addr.sun_path));
430 426 addr.sun_path[sizeof(addr.sun_path) - 1] = '\0';
431 427
432 428 int r = connect(fd, (struct sockaddr *)&addr, sizeof(addr));
433 429 if (r < 0) {
434 430 close(fd);
435 431 if (errno == ENOENT || errno == ECONNREFUSED)
436 432 return NULL;
437 433 abortmsgerrno("cannot connect to %s", addr.sun_path);
438 434 }
439 435 debugmsg("connected to %s", addr.sun_path);
440 436
441 437 hgclient_t *hgc = mallocx(sizeof(hgclient_t));
442 438 memset(hgc, 0, sizeof(*hgc));
443 439 hgc->sockfd = fd;
444 440 initcontext(&hgc->ctx);
445 441
446 442 readhello(hgc);
447 443 if (!(hgc->capflags & CAP_RUNCOMMAND))
448 444 abortmsg("insufficient capability: runcommand");
449 445 if (hgc->capflags & CAP_ATTACHIO)
450 446 attachio(hgc);
451 447 if (hgc->capflags & CAP_CHDIR)
452 448 chdirtocwd(hgc);
453 449 if (hgc->capflags & CAP_SETUMASK)
454 450 forwardumask(hgc);
455 451
456 452 return hgc;
457 453 }
458 454
459 455 /*!
460 456 * Close connection and free allocated memory
461 457 */
462 458 void hgc_close(hgclient_t *hgc)
463 459 {
464 460 assert(hgc);
465 461 freecontext(&hgc->ctx);
466 462 close(hgc->sockfd);
467 463 free(hgc);
468 464 }
469 465
470 466 pid_t hgc_peerpid(const hgclient_t *hgc)
471 467 {
472 468 assert(hgc);
473 469 return hgc->pid;
474 470 }
475 471
476 472 /*!
477 473 * Send command line arguments to let the server load the repo config and check
478 474 * whether it can process our request directly or not.
479 475 * Make sure hgc_setenv is called before calling this.
480 476 *
481 477 * @return - NULL, the server believes it can handle our request, or does not
482 478 * support "validate" command.
483 479 * - a list of strings, the server probably cannot handle our request
484 480 * and it sent instructions telling us what to do next. See
485 481 * chgserver.py for possible instruction formats.
486 482 * the list should be freed by the caller.
487 483 * the last string is guaranteed to be NULL.
488 484 */
489 485 const char **hgc_validate(hgclient_t *hgc, const char *const args[],
490 486 size_t argsize)
491 487 {
492 488 assert(hgc);
493 489 if (!(hgc->capflags & CAP_VALIDATE))
494 490 return NULL;
495 491
496 492 packcmdargs(&hgc->ctx, args, argsize);
497 493 writeblockrequest(hgc, "validate");
498 494 handleresponse(hgc);
499 495
500 496 /* the server returns '\0' if it can handle our request */
501 497 if (hgc->ctx.datasize <= 1)
502 498 return NULL;
503 499
504 500 /* make sure the buffer is '\0' terminated */
505 501 enlargecontext(&hgc->ctx, hgc->ctx.datasize + 1);
506 502 hgc->ctx.data[hgc->ctx.datasize] = '\0';
507 503 return unpackcmdargsnul(&hgc->ctx);
508 504 }
509 505
510 506 /*!
511 507 * Execute the specified Mercurial command
512 508 *
513 509 * @return result code
514 510 */
515 511 int hgc_runcommand(hgclient_t *hgc, const char *const args[], size_t argsize)
516 512 {
517 513 assert(hgc);
518 514
519 515 packcmdargs(&hgc->ctx, args, argsize);
520 516 writeblockrequest(hgc, "runcommand");
521 517 handleresponse(hgc);
522 518
523 519 int32_t exitcode_n;
524 520 if (hgc->ctx.datasize != sizeof(exitcode_n)) {
525 521 abortmsg("unexpected size of exitcode");
526 522 }
527 523 memcpy(&exitcode_n, hgc->ctx.data, sizeof(exitcode_n));
528 524 return ntohl(exitcode_n);
529 525 }
530 526
531 527 /*!
532 528 * (Re-)send client's stdio channels so that the server can access to tty
533 529 */
534 530 void hgc_attachio(hgclient_t *hgc)
535 531 {
536 532 assert(hgc);
537 533 if (!(hgc->capflags & CAP_ATTACHIO))
538 534 return;
539 535 attachio(hgc);
540 536 }
541 537
542 538 /*!
543 539 * Get pager command for the given Mercurial command args
544 540 *
545 541 * If no pager enabled, returns NULL. The return value becomes invalid
546 542 * once you run another request to hgc.
547 543 */
548 544 const char *hgc_getpager(hgclient_t *hgc, const char *const args[],
549 545 size_t argsize)
550 546 {
551 547 assert(hgc);
552 548
553 549 if (!(hgc->capflags & CAP_GETPAGER))
554 550 return NULL;
555 551
556 552 packcmdargs(&hgc->ctx, args, argsize);
557 553 writeblockrequest(hgc, "getpager");
558 554 handleresponse(hgc);
559 555
560 556 if (hgc->ctx.datasize < 1 || hgc->ctx.data[0] == '\0')
561 557 return NULL;
562 558 enlargecontext(&hgc->ctx, hgc->ctx.datasize + 1);
563 559 hgc->ctx.data[hgc->ctx.datasize] = '\0';
564 560 return hgc->ctx.data;
565 561 }
566 562
567 563 /*!
568 564 * Update server's environment variables
569 565 *
570 566 * @param envp list of environment variables in "NAME=VALUE" format,
571 567 * terminated by NULL.
572 568 */
573 569 void hgc_setenv(hgclient_t *hgc, const char *const envp[])
574 570 {
575 571 assert(hgc && envp);
576 572 if (!(hgc->capflags & CAP_SETENV))
577 573 return;
578 574 packcmdargs(&hgc->ctx, envp, /*argsize*/ -1);
579 575 writeblockrequest(hgc, "setenv");
580 576 }
@@ -1,180 +1,190
1 1 /*
2 2 * Utility functions
3 3 *
4 4 * Copyright (c) 2011 Yuya Nishihara <yuya@tcha.org>
5 5 *
6 6 * This software may be used and distributed according to the terms of the
7 7 * GNU General Public License version 2 or any later version.
8 8 */
9 9
10 10 #include <errno.h>
11 #include <fcntl.h>
11 12 #include <signal.h>
12 13 #include <stdarg.h>
13 14 #include <stdio.h>
14 15 #include <stdlib.h>
15 16 #include <string.h>
16 17 #include <sys/types.h>
17 18 #include <sys/wait.h>
18 19 #include <unistd.h>
19 20
20 21 #include "util.h"
21 22
22 23 static int colorenabled = 0;
23 24
24 25 static inline void fsetcolor(FILE *fp, const char *code)
25 26 {
26 27 if (!colorenabled)
27 28 return;
28 29 fprintf(fp, "\033[%sm", code);
29 30 }
30 31
31 32 static void vabortmsgerrno(int no, const char *fmt, va_list args)
32 33 {
33 34 fsetcolor(stderr, "1;31");
34 35 fputs("chg: abort: ", stderr);
35 36 vfprintf(stderr, fmt, args);
36 37 if (no != 0)
37 38 fprintf(stderr, " (errno = %d, %s)", no, strerror(no));
38 39 fsetcolor(stderr, "");
39 40 fputc('\n', stderr);
40 41 exit(255);
41 42 }
42 43
43 44 void abortmsg(const char *fmt, ...)
44 45 {
45 46 va_list args;
46 47 va_start(args, fmt);
47 48 vabortmsgerrno(0, fmt, args);
48 49 va_end(args);
49 50 }
50 51
51 52 void abortmsgerrno(const char *fmt, ...)
52 53 {
53 54 int no = errno;
54 55 va_list args;
55 56 va_start(args, fmt);
56 57 vabortmsgerrno(no, fmt, args);
57 58 va_end(args);
58 59 }
59 60
60 61 static int debugmsgenabled = 0;
61 62
62 63 void enablecolor(void)
63 64 {
64 65 colorenabled = 1;
65 66 }
66 67
67 68 void enabledebugmsg(void)
68 69 {
69 70 debugmsgenabled = 1;
70 71 }
71 72
72 73 void debugmsg(const char *fmt, ...)
73 74 {
74 75 if (!debugmsgenabled)
75 76 return;
76 77
77 78 va_list args;
78 79 va_start(args, fmt);
79 80 fsetcolor(stderr, "1;30");
80 81 fputs("chg: debug: ", stderr);
81 82 vfprintf(stderr, fmt, args);
82 83 fsetcolor(stderr, "");
83 84 fputc('\n', stderr);
84 85 va_end(args);
85 86 }
86 87
87 88 void fchdirx(int dirfd)
88 89 {
89 90 int r = fchdir(dirfd);
90 91 if (r == -1)
91 92 abortmsgerrno("failed to fchdir");
92 93 }
93 94
95 void fsetcloexec(int fd)
96 {
97 int flags = fcntl(fd, F_GETFD);
98 if (flags < 0)
99 abortmsgerrno("cannot get flags of fd %d", fd);
100 if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) < 0)
101 abortmsgerrno("cannot set flags of fd %d", fd);
102 }
103
94 104 void *mallocx(size_t size)
95 105 {
96 106 void *result = malloc(size);
97 107 if (!result)
98 108 abortmsg("failed to malloc");
99 109 return result;
100 110 }
101 111
102 112 void *reallocx(void *ptr, size_t size)
103 113 {
104 114 void *result = realloc(ptr, size);
105 115 if (!result)
106 116 abortmsg("failed to realloc");
107 117 return result;
108 118 }
109 119
110 120 /*
111 121 * Execute a shell command in mostly the same manner as system(), with the
112 122 * give environment variables, after chdir to the given cwd. Returns a status
113 123 * code compatible with the Python subprocess module.
114 124 */
115 125 int runshellcmd(const char *cmd, const char *envp[], const char *cwd)
116 126 {
117 127 enum { F_SIGINT = 1, F_SIGQUIT = 2, F_SIGMASK = 4, F_WAITPID = 8 };
118 128 unsigned int doneflags = 0;
119 129 int status = 0;
120 130 struct sigaction newsa, oldsaint, oldsaquit;
121 131 sigset_t oldmask;
122 132
123 133 /* block or mask signals just as system() does */
124 134 memset(&newsa, 0, sizeof(newsa));
125 135 newsa.sa_handler = SIG_IGN;
126 136 newsa.sa_flags = 0;
127 137 if (sigemptyset(&newsa.sa_mask) < 0)
128 138 goto done;
129 139 if (sigaction(SIGINT, &newsa, &oldsaint) < 0)
130 140 goto done;
131 141 doneflags |= F_SIGINT;
132 142 if (sigaction(SIGQUIT, &newsa, &oldsaquit) < 0)
133 143 goto done;
134 144 doneflags |= F_SIGQUIT;
135 145
136 146 if (sigaddset(&newsa.sa_mask, SIGCHLD) < 0)
137 147 goto done;
138 148 if (sigprocmask(SIG_BLOCK, &newsa.sa_mask, &oldmask) < 0)
139 149 goto done;
140 150 doneflags |= F_SIGMASK;
141 151
142 152 pid_t pid = fork();
143 153 if (pid < 0)
144 154 goto done;
145 155 if (pid == 0) {
146 156 sigaction(SIGINT, &oldsaint, NULL);
147 157 sigaction(SIGQUIT, &oldsaquit, NULL);
148 158 sigprocmask(SIG_SETMASK, &oldmask, NULL);
149 159 if (cwd && chdir(cwd) < 0)
150 160 _exit(127);
151 161 const char *argv[] = {"sh", "-c", cmd, NULL};
152 162 if (envp) {
153 163 execve("/bin/sh", (char **)argv, (char **)envp);
154 164 } else {
155 165 execv("/bin/sh", (char **)argv);
156 166 }
157 167 _exit(127);
158 168 } else {
159 169 if (waitpid(pid, &status, 0) < 0)
160 170 goto done;
161 171 doneflags |= F_WAITPID;
162 172 }
163 173
164 174 done:
165 175 if (doneflags & F_SIGINT)
166 176 sigaction(SIGINT, &oldsaint, NULL);
167 177 if (doneflags & F_SIGQUIT)
168 178 sigaction(SIGQUIT, &oldsaquit, NULL);
169 179 if (doneflags & F_SIGMASK)
170 180 sigprocmask(SIG_SETMASK, &oldmask, NULL);
171 181
172 182 /* no way to report other errors, use 127 (= shell termination) */
173 183 if (!(doneflags & F_WAITPID))
174 184 return 127;
175 185 if (WIFEXITED(status))
176 186 return WEXITSTATUS(status);
177 187 if (WIFSIGNALED(status))
178 188 return -WTERMSIG(status);
179 189 return 127;
180 190 }
@@ -1,32 +1,33
1 1 /*
2 2 * Utility functions
3 3 *
4 4 * Copyright (c) 2011 Yuya Nishihara <yuya@tcha.org>
5 5 *
6 6 * This software may be used and distributed according to the terms of the
7 7 * GNU General Public License version 2 or any later version.
8 8 */
9 9
10 10 #ifndef UTIL_H_
11 11 #define UTIL_H_
12 12
13 13 #ifdef __GNUC__
14 14 #define PRINTF_FORMAT_ __attribute__((format(printf, 1, 2)))
15 15 #else
16 16 #define PRINTF_FORMAT_
17 17 #endif
18 18
19 19 void abortmsg(const char *fmt, ...) PRINTF_FORMAT_;
20 20 void abortmsgerrno(const char *fmt, ...) PRINTF_FORMAT_;
21 21
22 22 void enablecolor(void);
23 23 void enabledebugmsg(void);
24 24 void debugmsg(const char *fmt, ...) PRINTF_FORMAT_;
25 25
26 26 void fchdirx(int dirfd);
27 void fsetcloexec(int fd);
27 28 void *mallocx(size_t size);
28 29 void *reallocx(void *ptr, size_t size);
29 30
30 31 int runshellcmd(const char *cmd, const char *envp[], const char *cwd);
31 32
32 33 #endif /* UTIL_H_ */
General Comments 0
You need to be logged in to leave comments. Login now