3 * $Id: sw_rsh.c,v 1.1 1999/06/02 16:53:34 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 /*----- Revision history --------------------------------------------------*
32 * Revision 1.1 1999/06/02 16:53:34 mdw
37 /*----- Header files ------------------------------------------------------*/
49 #include <sys/types.h>
54 #include <sys/socket.h>
58 extern char **environ;
61 #include <mLib/alloc.h>
62 #include <mLib/dstr.h>
64 #include <mLib/mdwopt.h>
65 #include <mLib/quis.h>
66 #include <mLib/report.h>
75 /*----- Data structures ---------------------------------------------------*/
77 typedef unsigned char octet;
81 typedef struct pkhead {
86 /*----- Static variables --------------------------------------------------*/
88 static int handler = 0;
89 static rcmd *rcmds = RCMD_LINK;
91 /*----- Packet interface --------------------------------------------------*/
95 * Arguments: @sw_remote@ = pointer to the remote block
96 * @int type@ = packet type to send
97 * @const void *p@ = pointer to packet data
98 * @size_t sz@ = size of data to send
100 * Returns: Zero if it worked, nonzero otherwise.
102 * Use: Sends a data packet. If the type is `data', then `sz' may be
103 * arbitrarily large and is divided into small eenough chunks.
104 * Otherwise it's an error to send a packet that's too big.
107 int pksend(sw_remote *r, int type, const void *p, size_t sz)
113 /* --- Sort out error conditions --- */
115 if (sz > PKMAX && type != PKTYPE_DATA) {
120 /* --- Main output loop --- */
125 /* --- Set up the packet header --- */
127 chunk = (sz > PKMAX ? PKMAX : sz);
128 h.len[0] = chunk & 0xff;
129 h.len[1] = (chunk >> 8) & 0xff;
131 /* --- Write the packet header --- */
134 if (write(r->fdout, &h, PKHEADSZ) < PKHEADSZ) {
140 /* --- Write the payload, if there is one --- *
142 * Maybe the OS won't want to bite it all off in one go.
146 ssize_t n = write(r->fdout, q, chunk);
147 if (n < 0 && errno != EINTR)
162 /* --- @pkrecv@ --- *
164 * Arguments: @sw_remote *r@ = remote block
166 * Returns: Packet type received, or @-1@ for an error.
168 * Use: Receives a packet from the remote host. The packet data is
169 * placed in the block's buffer, the block's packet length is
170 * diddled appropriately.
173 int pkrecv(sw_remote *r)
180 /* --- Read the packet header --- */
185 n = read(r->fdin, p, sz);
186 if (n < 0 && errno != EINTR)
196 /* --- Hack for error messages --- *
198 * If it doesn't look like a valid packet, read a `chunk' and pretend it's
199 * data. This isn't too bad, because all the packet types are control
200 * codes, and are unlikely to be in a textual message.
202 * Normally what happens here is that something sitting before the `sw'
203 * program fails, reports a plain textual error, and exits. Grabbing the
204 * `last gasp' like this, then, traps that error message and allows
205 * something to report it. The rest ought to be completely silent, so I
206 * get an `unexpected eof' and then drop everything.
208 * This is certainly better than the behaviour otherwise, which is an
209 * @E2BIG@ message reported when the packet size is really ASCII
213 if (h.type >= PKTYPE_BOGUS) {
214 memcpy(r->buf, &h, PKHEADSZ);
215 n = read(r->fdin, r->buf + PKHEADSZ, sizeof(r->buf) - PKHEADSZ);
218 r->sz = n + PKHEADSZ;
219 return (PKTYPE_DATA);
222 /* --- Sort out what's going on --- */
224 sz = h.len[0] | (h.len[1] << 8);
233 /* --- Read the packet payload --- */
237 n = read(r->fdin, p, sz);
238 if (n < 0 && errno != EINTR)
251 /*----- Error reporting and exit statuses --------------------------------*/
253 /* --- @swexit@ --- *
255 * Arguments: @sw_remote *r@ = remote context
256 * @int status@ = exit status to return
260 * Use: Reports the exit status via packet protocol and quits.
263 void swexit(sw_remote *r, int status)
265 unsigned char s = status;
266 pksend(r, PKTYPE_STATUS, &s, 1);
270 /* --- @swsignal@ --- *
272 * Arguments: @sw_remote *r@ = remote context
273 * @int sig@ = signal ocurrence to return
277 * Use: Reports a signalled-to-death status via packet protocol and
281 void swsignal(sw_remote *r, int sig)
283 #if defined(HAVE_STRSIGNAL)
284 char *s = strsignal(sig);
285 #elif defined(HAVE__SYS_SIGLIST)
286 char *s = _sys_siglist[sig];
289 sprintf(s, "signal %i", sig);
292 pksend(r, PKTYPE_STATUS, s, strlen(s) + 1);
296 /* --- @swwait@ --- *
298 * Arguments: @sw_remote *r@ = remote context
299 * @int status@ = status answer from @wait@(2)
303 * Use: Reports a child's demise appropriately, and quits.
306 void swwait(sw_remote *r, int status)
308 if (WIFEXITED(status))
309 swexit(r, WEXITSTATUS(status));
310 else if (WIFSIGNALED(status))
311 swsignal(r, WTERMSIG(status));
316 /* --- @swvprintf@ --- *
318 * Arguments: @sw_remote *r@ = remote context
319 * @const char *format@ = format string
320 * @va_list ap@ = things to format
324 * Use: Writes a string to the remote end. This is the low-level bit
328 void swvprintf(sw_remote *r, const char *format, va_list ap)
331 dstr_vputf(&d, format, ap);
332 pksend(r, PKTYPE_DATA, d.buf, d.len);
336 /* --- @swprintf@ --- *
338 * Arguments: @sw_remote *r@ = remote context
339 * @const char *format@ = format string
340 * @...@ = other arguments
344 * Use: Writes a string to the remote end.
347 void swprintf(sw_remote *r, const char *format, ...)
350 va_start(ap, format);
351 swvprintf(r, format, ap);
357 * Arguments: @sw_remote *r@ = remote context
358 * @int status@ = exit status to report
359 * @const char *format@ = format string to fill in
360 * @...@ = other arguments
364 * Use: Reports a message and quits.
367 void swdie(sw_remote *r, int status, const char *format, ...)
372 va_start(ap, format);
373 dstr_putf(&d, "%s [remote]: ", QUIS);
374 dstr_vputf(&d, format, ap);
378 pksend(r, PKTYPE_DATA, d.buf, d.len);
383 /*----- Command handling and dispatch -------------------------------------*/
385 /* --- @remote@ --- *
387 * Arguments: @sw_remote *r@ = pointer to remote block
388 * @const char *cmd@ = command to run
389 * @char *argv[]@ = argument array
390 * @char *env[]@ = environment variables
392 * Returns: Doesn't. Reports an exit status through packet protocol and
395 * Use: Dispatches a remote command. At this point, the two code
396 * paths for local and remote invokation have joined again.
399 static void remote(sw_remote *r, const char *cmd, char *argv[], char *env[])
401 struct rcmd *p, *chosen = 0;
402 size_t sz = strlen(cmd);
404 /* --- Make sure that I can get the exit status of children --- */
406 signal(SIGCHLD, SIG_DFL);
408 /* --- Fix up the environment --- */
414 if (env != environ) {
416 env_import(&t, environ);
418 env_put(&t, "SW_ARCH", ARCH);
419 env_file(&t, DATADIR "/sw-env");
420 env = env_export(&t);
423 /* --- Dispatch to the command handler --- */
425 for (p = rcmds; p; p = p->next) {
426 if (strncmp(cmd, p->name, sz) == 0) {
427 if (p->name[sz] == 0) {
431 swdie(r, 1, "ambiguous remote command name `%s'", cmd);
437 swdie(r, 1, "unknown remote command name `%s'", cmd);
438 chosen->rcmd(r, argv, env);
441 /*----- Remote invocation -------------------------------------------------*/
443 /* --- @sendargv@ --- *
445 * Arguments: @sw_remote *r@ = pointer to the remote context
446 * @int type@ = packet type to send with
447 * @char *v[]@ = pointer to the array to send
449 * Returns: Zero if OK, nonzero if it failed.
451 * Use: Sends something @argv@-shaped; i.e., an array of strings
452 * terminated by a null pointer.
455 static int sendargv(sw_remote *r, int type, char *v[])
462 d.len++; /* Make the null `real' */
465 e = pksend(r, type, d.buf, d.len);
470 /* --- @snarfargv@ --- *
472 * Arguments: @const char *buf@ = pointer to buffer
473 * @size_t sz@ = size of buffer
475 * Returns: Pointer to argument array (allocated with @malloc@).
477 * Use: Snarfs the null-terminated strings in the buffer and returns
478 * an array of them. The whole lot, strings and array, is
479 * returned in one big chunk allocated from the heap. Note that
480 * this means it's OK to throw the initial buffer away.
483 static char **snarfargv(const char *buf, size_t sz)
485 /* --- Initial setup --- */
492 /* --- Pass one: count the number of arguments --- */
508 /* --- Allocate memory for everything --- */
510 v = xmalloc((c + 1) * sizeof(char *) + sz + 1);
511 q = (char *)(v + c + 1);
514 /* --- Pass two: set up the arrays --- */
536 /* --- @swrsh_remote@ --- *
538 * Arguments: @const char *cmd@ = the command to perform
540 * Returns: Doesn't. Reports an exit status through packet protocol and
543 * Use: Handles the remote end of a remote job invokation.
546 void swrsh_remote(const char *cmd)
549 static char *dummy = 0;
556 /* --- Read packets from the remote host --- */
562 swdie(&r, 1, "error reading packet: %s", strerror(errno));
569 argv = snarfargv(r.buf, r.sz);
574 env = snarfargv(r.buf, r.sz);
580 dir = xstrdup(r.buf);
586 swdie(&r, 1, "internal error: unexpected packet");
591 /* --- Sort out any missing arguments --- */
601 /* --- Run the command --- */
604 remote(&r, cmd, argv, env);
605 CATCH switch (exc_type) {
607 static char msg[] = "\nsw [remote]: not enough memory\n";
608 pksend(&r, PKTYPE_DATA, msg, sizeof(msg) - 1);
612 swdie(&r, 1, "uncaught exception, type = %lx", exc_type);
616 /*----- Starting remote jobs ----------------------------------------------*/
618 /* --- @sigchld@ --- *
620 * Arguments: @int sig@ = the signal number
624 * Use: Catches @SIGCHLD@ and reaps any children that have lost.
627 static void sigchld(int sig)
631 while (waitpid(-1, &status, WNOHANG) > 0) {
632 if (WIFEXITED(status)) {
633 fprintf(stderr, "reap child with exit status %i\n",
634 WEXITSTATUS(status));
635 } else if (WIFSIGNALED(status)) {
636 fprintf(stderr, "reap child killed by signal %s\n",
637 strsignal(WTERMSIG(status)));
639 fprintf(stderr, "reaped bizarre child which is still alive\n");
642 while (waitpid(-1, 0, WNOHANG) > 0)
649 * Arguments: @sw_remote *r@ = remote process block to look after
650 * @const char *host@ = host to run on (0 for this one)
651 * @const char *cmd@ = remote command to run
652 * @char *argv[]@ = arguments to pass on
654 * Returns: Zero if it worked, nonzero if not.
656 * Use: Runs a command on a remote host. The argument array is
657 * mangled to come out OK at the far end. The environment and
658 * current directory are also passed along, and pop out the
659 * other end unmolested.
662 int swrsh(sw_remote *r, const char *host, const char *cmd, char *argv[])
667 /* --- Get a socket pair for communicating with the other end --- */
669 if (socketpair(PF_UNIX, SOCK_STREAM, 0, sk))
672 /* --- Set up a signal handler --- */
676 sa.sa_handler = sigchld;
678 sigemptyset(&sa.sa_mask);
679 sigaction(SIGCHLD, &sa, 0);
683 /* --- Fork off a child to cope with stuff --- */
689 /* --- Handle the child process --- *
691 * If this is a local job, then just loop around inside to handle the
692 * `remote' command. Otherwise crank up `rsh' and pass the command over to
693 * a remote copy of myself.
695 * (Why do I need a separate process for local jobs? I don't really, but
696 * it makes everything much simpler when running multiple jobs at the same
703 /* --- Child end of a local job --- */
706 r->fdin = r->fdout = sk[1];
707 remote(r, cmd, argv, environ);
710 /* --- Local child end of a remote job --- */
719 rsh = getenv("SW_RSH");
722 execlp(rsh, rsh, host, PATH_SW, "--remote", cmd, (char *)0);
725 /* --- I don't expect either to come back --- */
730 /* --- Local sort out of what to do --- *
732 * Either way, I've now got a socket tied to something which speaks my
733 * communication protocol. However, if this is a local job, then I can get
734 * going right away; otherwise, I've got to transmit various bits of
735 * information over the protocol.
738 r->fdin = r->fdout = sk[0];
743 if (!getcwd(buf, sizeof(buf)))
745 sendargv(r, PKTYPE_ARGS, argv);
746 sendargv(r, PKTYPE_ENV, environ);
747 pksend(r, PKTYPE_DIR, buf, strlen(buf) + 1);
748 pksend(r, PKTYPE_GO, 0, 0);
751 /* --- Ready to rock'n'roll --- */
756 /* --- Tidy up if it failed --- */
765 /*----- Subcommands -------------------------------------------------------*/
767 /* --- @swrsh_rsh@ --- */
769 void rsw_rsh(sw_remote *r, char *argv[], char *env[])
775 /* --- Create a pipe --- */
778 swdie(r, 1, "couldn't create pipe: %s", strerror(errno));
780 /* --- Start the child process up --- */
784 swdie(r, 1, "fork failed: %s", strerror(errno));
788 /* --- Use my new environment --- */
790 environ = env; /* Yuk. */
792 /* --- Fiddle with pipe file descriptors --- */
800 /* --- Make sure it doesn't get any input --- */
803 fd = open("/dev/null", O_RDONLY);
809 /* --- Run the program --- */
811 execvp(argv[0], argv);
812 die(1, "couldn't exec `%s': %s", argv[0], strerror(errno));
815 /* --- Read the data from the pipe until it closes --- */
819 ssize_t n = read(pfd[0], r->buf, sizeof(r->buf));
821 swdie(r, 1, "read error: %s", strerror(errno));
825 pksend(r, PKTYPE_DATA, r->buf, n);
829 /* --- Finally, reap the exit status and pass it on --- */
836 swdie(r, 1, "error reaping child: %s", strerror(errno));
841 /* --- @sw_rsh@ --- */
843 int sw_rsh(int argc, char *argv[])
849 /* --- Check the arguments --- */
852 die(1, "Usage: rsh HOST|ARCH COMMAND [ARGS...]");
854 /* --- Translate architecture names into hostnames --- */
856 if (strcmp(argv[1], "-") == 0)
859 archent *a = arch_lookup(argv[1], 0);
862 else if (a->flags & archFlag_home)
868 /* --- Start the remote process --- */
870 if (swrsh(&r, h, "rsh", argv + 2))
871 die(1, "remote shell failed: %s", strerror(errno));
873 /* --- Cope with packets from the remote process --- */
880 die(1, "error reading packet: %s", strerror(errno));
882 write(STDOUT_FILENO, r.buf, r.sz);
888 moan("command exited due to signal: %s", r.buf);
891 moan("command exited with status %i", r.buf[0]);
895 moan("command exited unexpectedly");
898 die(1, "unexpected packet type");
902 /* --- Finished --- */
909 /*----- That's all, folks -------------------------------------------------*/