3 * $Id: sw_rsh.c,v 1.8 2004/04/08 01:52:19 mdw Exp $
10 /*----- Licensing notice --------------------------------------------------*
12 * This file is part of sw-tools.
14 * sw-tools is free software; you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation; either version 2 of the License, or
17 * (at your option) any later version.
19 * sw-tools is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
24 * You should have received a copy of the GNU General Public License
25 * along with sw-tools; if not, write to the Free Software Foundation,
26 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
29 /*----- Header files ------------------------------------------------------*/
41 #include <sys/types.h>
46 #include <sys/socket.h>
50 extern char **environ;
53 #include <mLib/alloc.h>
54 #include <mLib/bits.h>
55 #include <mLib/dstr.h>
57 #include <mLib/mdwopt.h>
58 #include <mLib/quis.h>
59 #include <mLib/report.h>
68 /*----- Data structures ---------------------------------------------------*/
72 /*----- Static variables --------------------------------------------------*/
74 static int handler = 0;
75 static rcmd *rcmds = RCMD_LINK;
77 /*----- Packet interface --------------------------------------------------*/
81 * Arguments: @sw_remote@ = pointer to the remote block
82 * @int type@ = packet type to send
83 * @const void *p@ = pointer to packet data
84 * @size_t sz@ = size of data to send
86 * Returns: Zero if it worked, nonzero otherwise.
88 * Use: Sends a data packet. If the type is `data', then `sz' may be
89 * arbitrarily large and is divided into small enough chunks.
90 * Otherwise it's an error to send a packet that's too big.
93 int pksend(sw_remote *r, int type, const void *p, size_t sz)
99 /* --- Sort out error conditions --- */
101 if (sz > PKMAX && type != PKTYPE_DATA) {
106 /* --- Main output loop --- */
111 /* --- Set up the packet header --- */
113 chunk = (sz > PKMAX ? PKMAX : sz);
116 /* --- Write the packet header --- */
119 if (write(r->fdout, &h, PKHEADSZ) < PKHEADSZ) {
125 /* --- Write the payload, if there is one --- *
127 * Maybe the OS won't want to bite it all off in one go.
131 ssize_t n = write(r->fdout, q, chunk);
132 if (n < 0 && errno != EINTR)
147 /* --- @pkrecv@ --- *
149 * Arguments: @sw_remote *r@ = remote block
151 * Returns: Packet type received, or @-1@ for an error.
153 * Use: Receives a packet from the remote host. The packet data is
154 * placed in the block's buffer, the block's packet length is
155 * diddled appropriately.
158 int pkrecv(sw_remote *r)
165 /* --- Read the packet header --- */
170 n = read(r->fdin, p, sz);
171 if (n < 0 && errno != EINTR)
181 /* --- Hack for error messages --- *
183 * If it doesn't look like a valid packet, read a `chunk' and pretend it's
184 * data. This isn't too bad, because all the packet types are control
185 * codes, and are unlikely to be in a textual message.
187 * Normally what happens here is that something sitting before the `sw'
188 * program fails, reports a plain textual error, and exits. Grabbing the
189 * `last gasp' like this, then, traps that error message and allows
190 * something to report it. The rest ought to be completely silent, so I
191 * get an `unexpected eof' and then drop everything.
193 * This is certainly better than the behaviour otherwise, which is an
194 * @E2BIG@ message reported when the packet size is really ASCII
198 if (h[2] >= PKTYPE_BOGUS) {
199 memcpy(r->buf, &h, PKHEADSZ);
200 n = read(r->fdin, r->buf + PKHEADSZ, sizeof(r->buf) - PKHEADSZ);
203 r->sz = n + PKHEADSZ;
204 return (PKTYPE_DATA);
207 /* --- Sort out what's going on --- */
218 /* --- Read the packet payload --- */
222 n = read(r->fdin, p, sz);
223 if (n < 0 && errno != EINTR)
236 /*----- Error reporting and exit statuses --------------------------------*/
238 /* --- @swexit@ --- *
240 * Arguments: @sw_remote *r@ = remote context
241 * @int status@ = exit status to return
245 * Use: Reports the exit status via packet protocol and quits.
248 void swexit(sw_remote *r, int status)
250 unsigned char s = status;
251 pksend(r, PKTYPE_STATUS, &s, 1);
255 /* --- @swsignal@ --- *
257 * Arguments: @sw_remote *r@ = remote context
258 * @int sig@ = signal ocurrence to return
262 * Use: Reports a signalled-to-death status via packet protocol and
266 void swsignal(sw_remote *r, int sig)
268 #if defined(HAVE_STRSIGNAL)
269 char *s = strsignal(sig);
270 #elif defined(HAVE__SYS_SIGLIST)
271 char *s = _sys_siglist[sig];
274 sprintf(s, "signal %i", sig);
277 pksend(r, PKTYPE_STATUS, s, strlen(s) + 1);
281 /* --- @swwait@ --- *
283 * Arguments: @sw_remote *r@ = remote context
284 * @int status@ = status answer from @wait@(2)
288 * Use: Reports a child's demise appropriately, and quits.
291 void swwait(sw_remote *r, int status)
293 if (WIFEXITED(status))
294 swexit(r, WEXITSTATUS(status));
295 else if (WIFSIGNALED(status))
296 swsignal(r, WTERMSIG(status));
301 /* --- @swvprintf@ --- *
303 * Arguments: @sw_remote *r@ = remote context
304 * @const char *format@ = format string
305 * @va_list ap@ = things to format
309 * Use: Writes a string to the remote end. This is the low-level bit
313 void swvprintf(sw_remote *r, const char *format, va_list ap)
316 dstr_vputf(&d, format, ap);
317 pksend(r, PKTYPE_DATA, d.buf, d.len);
321 /* --- @swprintf@ --- *
323 * Arguments: @sw_remote *r@ = remote context
324 * @const char *format@ = format string
325 * @...@ = other arguments
329 * Use: Writes a string to the remote end.
332 void swprintf(sw_remote *r, const char *format, ...)
335 va_start(ap, format);
336 swvprintf(r, format, ap);
342 * Arguments: @sw_remote *r@ = remote context
343 * @int status@ = exit status to report
344 * @const char *format@ = format string to fill in
345 * @...@ = other arguments
349 * Use: Reports a message and quits.
352 void swdie(sw_remote *r, int status, const char *format, ...)
357 va_start(ap, format);
358 dstr_putf(&d, "%s [remote]: ", QUIS);
359 dstr_vputf(&d, format, ap);
363 pksend(r, PKTYPE_DATA, d.buf, d.len);
368 /*----- Command handling and dispatch -------------------------------------*/
370 /* --- @remote@ --- *
372 * Arguments: @sw_remote *r@ = pointer to remote block
373 * @const char *cmd@ = command to run
374 * @char *argv[]@ = argument array
375 * @char *env[]@ = environment variables
377 * Returns: Doesn't. Reports an exit status through packet protocol and
380 * Use: Dispatches a remote command. At this point, the two code
381 * paths for local and remote invokation have joined again.
384 static void remote(sw_remote *r, const char *cmd, char *argv[], char *env[])
386 struct rcmd *p, *chosen = 0;
387 size_t sz = strlen(cmd);
389 /* --- Make sure that I can get the exit status of children --- */
391 signal(SIGCHLD, SIG_DFL);
393 /* --- Fix up the environment --- */
399 if (env != environ) {
401 env_import(&t, environ);
403 env_put(&t, "SW_ARCH", ARCH);
404 env_file(&t, DATADIR "/sw-env");
405 env = env_export(&t);
408 /* --- Dispatch to the command handler --- */
410 for (p = rcmds; p; p = p->next) {
411 if (strncmp(cmd, p->name, sz) == 0) {
412 if (p->name[sz] == 0) {
416 swdie(r, 1, "ambiguous remote command name `%s'", cmd);
422 swdie(r, 1, "unknown remote command name `%s'", cmd);
423 chosen->rcmd(r, argv, env);
426 /*----- Remote invocation -------------------------------------------------*/
428 /* --- @sendargv@ --- *
430 * Arguments: @sw_remote *r@ = pointer to the remote context
431 * @int type@ = packet type to send with
432 * @char *v[]@ = pointer to the array to send
434 * Returns: Zero if OK, nonzero if it failed.
436 * Use: Sends something @argv@-shaped; i.e., an array of strings
437 * terminated by a null pointer.
440 static int sendargv(sw_remote *r, int type, char *v[])
447 d.len++; /* Make the null `real' */
450 e = pksend(r, type, d.buf, d.len);
455 /* --- @snarfargv@ --- *
457 * Arguments: @const char *buf@ = pointer to buffer
458 * @size_t sz@ = size of buffer
460 * Returns: Pointer to argument array (allocated with @malloc@).
462 * Use: Snarfs the null-terminated strings in the buffer and returns
463 * an array of them. The whole lot, strings and array, is
464 * returned in one big chunk allocated from the heap. Note that
465 * this means it's OK to throw the initial buffer away.
468 static char **snarfargv(const char *buf, size_t sz)
470 /* --- Initial setup --- */
477 /* --- Pass one: count the number of arguments --- */
493 /* --- Allocate memory for everything --- */
495 v = xmalloc((c + 1) * sizeof(char *) + sz + 1);
496 q = (char *)(v + c + 1);
499 /* --- Pass two: set up the arrays --- */
521 /* --- @swrsh_remote@ --- *
523 * Arguments: @const char *cmd@ = the command to perform
525 * Returns: Doesn't. Reports an exit status through packet protocol and
528 * Use: Handles the remote end of a remote job invokation.
531 void swrsh_remote(const char *cmd)
534 static char *dummy = 0;
541 /* --- Read packets from the remote host --- */
547 swdie(&r, 1, "error reading packet: %s", strerror(errno));
554 argv = snarfargv(r.buf, r.sz);
559 env = snarfargv(r.buf, r.sz);
565 dir = xstrdup(r.buf);
571 swdie(&r, 1, "internal error: unexpected packet");
576 /* --- Sort out any missing arguments --- */
586 /* --- Run the command --- */
589 remote(&r, cmd, argv, env);
590 CATCH switch (exc_type) {
592 static char msg[] = "\nsw [remote]: not enough memory\n";
593 pksend(&r, PKTYPE_DATA, msg, sizeof(msg) - 1);
597 swdie(&r, 1, "uncaught exception, type = %lx", exc_type);
601 /*----- Starting remote jobs ----------------------------------------------*/
603 /* --- @sigchld@ --- *
605 * Arguments: @int sig@ = the signal number
609 * Use: Catches @SIGCHLD@ and reaps any children that have lost.
612 static void sigchld(int sig)
617 while (waitpid(-1, &status, WNOHANG) > 0) {
618 if (WIFEXITED(status)) {
619 fprintf(stderr, "reap child with exit status %i\n",
620 WEXITSTATUS(status));
621 } else if (WIFSIGNALED(status)) {
622 fprintf(stderr, "reap child killed by signal %s\n",
623 strsignal(WTERMSIG(status)));
625 fprintf(stderr, "reaped bizarre child which is still alive\n");
628 while (waitpid(-1, 0, WNOHANG) > 0)
636 * Arguments: @sw_remote *r@ = remote process block to look after
637 * @const char *host@ = host to run on (0 for this one)
638 * @const char *cmd@ = remote command to run
639 * @char *argv[]@ = arguments to pass on
641 * Returns: Zero if it worked, nonzero if not.
643 * Use: Runs a command on a remote host. The argument array is
644 * mangled to come out OK at the far end. The environment and
645 * current directory are also passed along, and pop out the
646 * other end unmolested.
649 int swrsh(sw_remote *r, const char *host, const char *cmd, char *argv[])
654 /* --- Get a socket pair for communicating with the other end --- */
656 if (socketpair(PF_UNIX, SOCK_STREAM, 0, sk))
659 /* --- Set up a signal handler --- */
663 sa.sa_handler = sigchld;
664 sa.sa_flags = SA_NOCLDSTOP;
666 sa.sa_flags |= SA_RESTART;
668 sigemptyset(&sa.sa_mask);
669 sigaction(SIGCHLD, &sa, 0);
673 /* --- Fork off a child to cope with stuff --- */
679 /* --- Handle the child process --- *
681 * If this is a local job, then just loop around inside to handle the
682 * `remote' command. Otherwise crank up `rsh' and pass the command over to
683 * a remote copy of myself.
685 * (Why do I need a separate process for local jobs? I don't really, but
686 * it makes everything much simpler when running multiple jobs at the same
693 /* --- Child end of a local job --- */
695 signal(SIGINT, SIG_DFL);
696 signal(SIGQUIT, SIG_DFL);
699 r->fdin = r->fdout = sk[1];
700 remote(r, cmd, argv, environ);
703 /* --- Local child end of a remote job --- */
712 rsh = getenv("SW_RSH");
715 execlp(rsh, rsh, host, PATH_SW, "--remote", cmd, (char *)0);
718 /* --- I don't expect either to come back --- */
723 /* --- Local sort out of what to do --- *
725 * Either way, I've now got a socket tied to something which speaks my
726 * communication protocol. However, if this is a local job, then I can get
727 * going right away; otherwise, I've got to transmit various bits of
728 * information over the protocol.
731 r->fdin = r->fdout = sk[0];
736 if (!getcwd(buf, sizeof(buf)))
738 sendargv(r, PKTYPE_ARGS, argv);
739 sendargv(r, PKTYPE_ENV, environ);
740 pksend(r, PKTYPE_DIR, buf, strlen(buf) + 1);
741 pksend(r, PKTYPE_GO, 0, 0);
744 /* --- Ready to rock'n'roll --- */
749 /* --- Tidy up if it failed --- */
758 /*----- Subcommands -------------------------------------------------------*/
760 /* --- @swrsh_rsh@ --- */
762 void rsw_rsh(sw_remote *r, char *argv[], char *env[])
768 /* --- Create a pipe --- */
771 swdie(r, 1, "couldn't create pipe: %s", strerror(errno));
773 /* --- Start the child process up --- */
777 swdie(r, 1, "fork failed: %s", strerror(errno));
781 /* --- Use my new environment --- */
783 environ = env; /* Yuk. */
785 /* --- Fiddle with pipe file descriptors --- */
793 /* --- Make sure it doesn't get any input --- */
796 fd = open("/dev/null", O_RDONLY);
802 /* --- Run the program --- */
804 execvp(argv[0], argv);
805 die(1, "couldn't exec `%s': %s", argv[0], strerror(errno));
808 /* --- Read the data from the pipe until it closes --- */
812 ssize_t n = read(pfd[0], r->buf, sizeof(r->buf));
814 swdie(r, 1, "read error: %s", strerror(errno));
818 pksend(r, PKTYPE_DATA, r->buf, n);
822 /* --- Finally, reap the exit status and pass it on --- */
829 swdie(r, 1, "error reaping child: %s", strerror(errno));
834 /* --- @sw_rsh@ --- */
836 int sw_rsh(int argc, char *argv[])
842 /* --- Check the arguments --- */
845 die(1, "Usage: rsh HOST|ARCH COMMAND [ARGS...]");
847 /* --- Translate architecture names into hostnames --- */
849 if (strcmp(argv[1], "-") == 0)
852 archent *a = arch_lookup(argv[1], 0);
855 else if (a->flags & archFlag_home)
861 /* --- Start the remote process --- */
863 if (swrsh(&r, h, "rsh", argv + 2))
864 die(1, "remote shell failed: %s", strerror(errno));
866 /* --- Cope with packets from the remote process --- */
873 die(1, "error reading packet: %s", strerror(errno));
875 write(STDOUT_FILENO, r.buf, r.sz);
881 moan("command exited due to signal: %s", r.buf);
884 moan("command exited with status %i", r.buf[0]);
888 moan("command exited unexpectedly");
891 die(1, "unexpected packet type");
895 /* --- Finished --- */
902 /*----- That's all, folks -------------------------------------------------*/