3 * $Id: sw_rsh.c,v 1.3 1999/06/18 18:58:54 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.3 1999/06/18 18:58:54 mdw
33 * Signal handling fixes.
35 * Revision 1.2 1999/06/02 17:03:29 mdw
36 * Fix use of `octet' now that mLib includes `bits.h' (as of version 1.3.5
37 * release). Also use the mLib load and store macros rather than doing it
40 * Revision 1.1.1.1 1999/06/02 16:53:34 mdw
45 /*----- Header files ------------------------------------------------------*/
57 #include <sys/types.h>
62 #include <sys/socket.h>
66 extern char **environ
;
69 #include <mLib/alloc.h>
70 #include <mLib/bits.h>
71 #include <mLib/dstr.h>
73 #include <mLib/mdwopt.h>
74 #include <mLib/quis.h>
75 #include <mLib/report.h>
84 /*----- Data structures ---------------------------------------------------*/
88 typedef struct pkhead
{
93 /*----- Static variables --------------------------------------------------*/
95 static int handler
= 0;
96 static rcmd
*rcmds
= RCMD_LINK
;
98 /*----- Packet interface --------------------------------------------------*/
100 /* --- @pksend@ --- *
102 * Arguments: @sw_remote@ = pointer to the remote block
103 * @int type@ = packet type to send
104 * @const void *p@ = pointer to packet data
105 * @size_t sz@ = size of data to send
107 * Returns: Zero if it worked, nonzero otherwise.
109 * Use: Sends a data packet. If the type is `data', then `sz' may be
110 * arbitrarily large and is divided into small eenough chunks.
111 * Otherwise it's an error to send a packet that's too big.
114 int pksend(sw_remote
*r
, int type
, const void *p
, size_t sz
)
120 /* --- Sort out error conditions --- */
122 if (sz
> PKMAX
&& type
!= PKTYPE_DATA
) {
127 /* --- Main output loop --- */
132 /* --- Set up the packet header --- */
134 chunk
= (sz
> PKMAX ? PKMAX
: sz
);
135 STORE16(h
.len
, chunk
);
137 /* --- Write the packet header --- */
140 if (write(r
->fdout
, &h
, PKHEADSZ
) < PKHEADSZ
) {
146 /* --- Write the payload, if there is one --- *
148 * Maybe the OS won't want to bite it all off in one go.
152 ssize_t n
= write(r
->fdout
, q
, chunk
);
153 if (n
< 0 && errno
!= EINTR
)
168 /* --- @pkrecv@ --- *
170 * Arguments: @sw_remote *r@ = remote block
172 * Returns: Packet type received, or @-1@ for an error.
174 * Use: Receives a packet from the remote host. The packet data is
175 * placed in the block's buffer, the block's packet length is
176 * diddled appropriately.
179 int pkrecv(sw_remote
*r
)
186 /* --- Read the packet header --- */
191 n
= read(r
->fdin
, p
, sz
);
192 if (n
< 0 && errno
!= EINTR
)
202 /* --- Hack for error messages --- *
204 * If it doesn't look like a valid packet, read a `chunk' and pretend it's
205 * data. This isn't too bad, because all the packet types are control
206 * codes, and are unlikely to be in a textual message.
208 * Normally what happens here is that something sitting before the `sw'
209 * program fails, reports a plain textual error, and exits. Grabbing the
210 * `last gasp' like this, then, traps that error message and allows
211 * something to report it. The rest ought to be completely silent, so I
212 * get an `unexpected eof' and then drop everything.
214 * This is certainly better than the behaviour otherwise, which is an
215 * @E2BIG@ message reported when the packet size is really ASCII
219 if (h
.type
>= PKTYPE_BOGUS
) {
220 memcpy(r
->buf
, &h
, PKHEADSZ
);
221 n
= read(r
->fdin
, r
->buf
+ PKHEADSZ
, sizeof(r
->buf
) - PKHEADSZ
);
224 r
->sz
= n
+ PKHEADSZ
;
225 return (PKTYPE_DATA
);
228 /* --- Sort out what's going on --- */
239 /* --- Read the packet payload --- */
243 n
= read(r
->fdin
, p
, sz
);
244 if (n
< 0 && errno
!= EINTR
)
257 /*----- Error reporting and exit statuses --------------------------------*/
259 /* --- @swexit@ --- *
261 * Arguments: @sw_remote *r@ = remote context
262 * @int status@ = exit status to return
266 * Use: Reports the exit status via packet protocol and quits.
269 void swexit(sw_remote
*r
, int status
)
271 unsigned char s
= status
;
272 pksend(r
, PKTYPE_STATUS
, &s
, 1);
276 /* --- @swsignal@ --- *
278 * Arguments: @sw_remote *r@ = remote context
279 * @int sig@ = signal ocurrence to return
283 * Use: Reports a signalled-to-death status via packet protocol and
287 void swsignal(sw_remote
*r
, int sig
)
289 #if defined(HAVE_STRSIGNAL)
290 char *s
= strsignal(sig
);
291 #elif defined(HAVE__SYS_SIGLIST)
292 char *s
= _sys_siglist
[sig
];
295 sprintf(s
, "signal %i", sig
);
298 pksend(r
, PKTYPE_STATUS
, s
, strlen(s
) + 1);
302 /* --- @swwait@ --- *
304 * Arguments: @sw_remote *r@ = remote context
305 * @int status@ = status answer from @wait@(2)
309 * Use: Reports a child's demise appropriately, and quits.
312 void swwait(sw_remote
*r
, int status
)
314 if (WIFEXITED(status
))
315 swexit(r
, WEXITSTATUS(status
));
316 else if (WIFSIGNALED(status
))
317 swsignal(r
, WTERMSIG(status
));
322 /* --- @swvprintf@ --- *
324 * Arguments: @sw_remote *r@ = remote context
325 * @const char *format@ = format string
326 * @va_list ap@ = things to format
330 * Use: Writes a string to the remote end. This is the low-level bit
334 void swvprintf(sw_remote
*r
, const char *format
, va_list ap
)
337 dstr_vputf(&d
, format
, ap
);
338 pksend(r
, PKTYPE_DATA
, d
.buf
, d
.len
);
342 /* --- @swprintf@ --- *
344 * Arguments: @sw_remote *r@ = remote context
345 * @const char *format@ = format string
346 * @...@ = other arguments
350 * Use: Writes a string to the remote end.
353 void swprintf(sw_remote
*r
, const char *format
, ...)
356 va_start(ap
, format
);
357 swvprintf(r
, format
, ap
);
363 * Arguments: @sw_remote *r@ = remote context
364 * @int status@ = exit status to report
365 * @const char *format@ = format string to fill in
366 * @...@ = other arguments
370 * Use: Reports a message and quits.
373 void swdie(sw_remote
*r
, int status
, const char *format
, ...)
378 va_start(ap
, format
);
379 dstr_putf(&d
, "%s [remote]: ", QUIS
);
380 dstr_vputf(&d
, format
, ap
);
384 pksend(r
, PKTYPE_DATA
, d
.buf
, d
.len
);
389 /*----- Command handling and dispatch -------------------------------------*/
391 /* --- @remote@ --- *
393 * Arguments: @sw_remote *r@ = pointer to remote block
394 * @const char *cmd@ = command to run
395 * @char *argv[]@ = argument array
396 * @char *env[]@ = environment variables
398 * Returns: Doesn't. Reports an exit status through packet protocol and
401 * Use: Dispatches a remote command. At this point, the two code
402 * paths for local and remote invokation have joined again.
405 static void remote(sw_remote
*r
, const char *cmd
, char *argv
[], char *env
[])
407 struct rcmd
*p
, *chosen
= 0;
408 size_t sz
= strlen(cmd
);
410 /* --- Make sure that I can get the exit status of children --- */
412 signal(SIGCHLD
, SIG_DFL
);
414 /* --- Fix up the environment --- */
420 if (env
!= environ
) {
422 env_import(&t
, environ
);
424 env_put(&t
, "SW_ARCH", ARCH
);
425 env_file(&t
, DATADIR
"/sw-env");
426 env
= env_export(&t
);
429 /* --- Dispatch to the command handler --- */
431 for (p
= rcmds
; p
; p
= p
->next
) {
432 if (strncmp(cmd
, p
->name
, sz
) == 0) {
433 if (p
->name
[sz
] == 0) {
437 swdie(r
, 1, "ambiguous remote command name `%s'", cmd
);
443 swdie(r
, 1, "unknown remote command name `%s'", cmd
);
444 chosen
->rcmd(r
, argv
, env
);
447 /*----- Remote invocation -------------------------------------------------*/
449 /* --- @sendargv@ --- *
451 * Arguments: @sw_remote *r@ = pointer to the remote context
452 * @int type@ = packet type to send with
453 * @char *v[]@ = pointer to the array to send
455 * Returns: Zero if OK, nonzero if it failed.
457 * Use: Sends something @argv@-shaped; i.e., an array of strings
458 * terminated by a null pointer.
461 static int sendargv(sw_remote
*r
, int type
, char *v
[])
468 d
.len
++; /* Make the null `real' */
471 e
= pksend(r
, type
, d
.buf
, d
.len
);
476 /* --- @snarfargv@ --- *
478 * Arguments: @const char *buf@ = pointer to buffer
479 * @size_t sz@ = size of buffer
481 * Returns: Pointer to argument array (allocated with @malloc@).
483 * Use: Snarfs the null-terminated strings in the buffer and returns
484 * an array of them. The whole lot, strings and array, is
485 * returned in one big chunk allocated from the heap. Note that
486 * this means it's OK to throw the initial buffer away.
489 static char **snarfargv(const char *buf
, size_t sz
)
491 /* --- Initial setup --- */
498 /* --- Pass one: count the number of arguments --- */
514 /* --- Allocate memory for everything --- */
516 v
= xmalloc((c
+ 1) * sizeof(char *) + sz
+ 1);
517 q
= (char *)(v
+ c
+ 1);
520 /* --- Pass two: set up the arrays --- */
542 /* --- @swrsh_remote@ --- *
544 * Arguments: @const char *cmd@ = the command to perform
546 * Returns: Doesn't. Reports an exit status through packet protocol and
549 * Use: Handles the remote end of a remote job invokation.
552 void swrsh_remote(const char *cmd
)
555 static char *dummy
= 0;
562 /* --- Read packets from the remote host --- */
568 swdie(&r
, 1, "error reading packet: %s", strerror(errno
));
575 argv
= snarfargv(r
.buf
, r
.sz
);
580 env
= snarfargv(r
.buf
, r
.sz
);
586 dir
= xstrdup(r
.buf
);
592 swdie(&r
, 1, "internal error: unexpected packet");
597 /* --- Sort out any missing arguments --- */
607 /* --- Run the command --- */
610 remote(&r
, cmd
, argv
, env
);
611 CATCH
switch (exc_type
) {
613 static char msg
[] = "\nsw [remote]: not enough memory\n";
614 pksend(&r
, PKTYPE_DATA
, msg
, sizeof(msg
) - 1);
618 swdie(&r
, 1, "uncaught exception, type = %lx", exc_type
);
622 /*----- Starting remote jobs ----------------------------------------------*/
624 /* --- @sigchld@ --- *
626 * Arguments: @int sig@ = the signal number
630 * Use: Catches @SIGCHLD@ and reaps any children that have lost.
633 static void sigchld(int sig
)
637 while (waitpid(-1, &status
, WNOHANG
) > 0) {
638 if (WIFEXITED(status
)) {
639 fprintf(stderr
, "reap child with exit status %i\n",
640 WEXITSTATUS(status
));
641 } else if (WIFSIGNALED(status
)) {
642 fprintf(stderr
, "reap child killed by signal %s\n",
643 strsignal(WTERMSIG(status
)));
645 fprintf(stderr
, "reaped bizarre child which is still alive\n");
648 while (waitpid(-1, 0, WNOHANG
) > 0)
655 * Arguments: @sw_remote *r@ = remote process block to look after
656 * @const char *host@ = host to run on (0 for this one)
657 * @const char *cmd@ = remote command to run
658 * @char *argv[]@ = arguments to pass on
660 * Returns: Zero if it worked, nonzero if not.
662 * Use: Runs a command on a remote host. The argument array is
663 * mangled to come out OK at the far end. The environment and
664 * current directory are also passed along, and pop out the
665 * other end unmolested.
668 int swrsh(sw_remote
*r
, const char *host
, const char *cmd
, char *argv
[])
673 /* --- Get a socket pair for communicating with the other end --- */
675 if (socketpair(PF_UNIX
, SOCK_STREAM
, 0, sk
))
678 /* --- Set up a signal handler --- */
682 sa
.sa_handler
= sigchld
;
683 sa
.sa_flags
= SA_NOCLDSTOP
;
685 sa
.sa_flags
|= SA_RESTART
;
687 sigemptyset(&sa
.sa_mask
);
688 sigaction(SIGCHLD
, &sa
, 0);
692 /* --- Fork off a child to cope with stuff --- */
698 /* --- Handle the child process --- *
700 * If this is a local job, then just loop around inside to handle the
701 * `remote' command. Otherwise crank up `rsh' and pass the command over to
702 * a remote copy of myself.
704 * (Why do I need a separate process for local jobs? I don't really, but
705 * it makes everything much simpler when running multiple jobs at the same
712 /* --- Child end of a local job --- */
715 r
->fdin
= r
->fdout
= sk
[1];
716 signal(SIGINT
, SIG_DFL
);
717 signal(SIGQUIT
, SIG_DFL
);
718 remote(r
, cmd
, argv
, environ
);
721 /* --- Local child end of a remote job --- */
730 rsh
= getenv("SW_RSH");
733 execlp(rsh
, rsh
, host
, PATH_SW
, "--remote", cmd
, (char *)0);
736 /* --- I don't expect either to come back --- */
741 /* --- Local sort out of what to do --- *
743 * Either way, I've now got a socket tied to something which speaks my
744 * communication protocol. However, if this is a local job, then I can get
745 * going right away; otherwise, I've got to transmit various bits of
746 * information over the protocol.
749 r
->fdin
= r
->fdout
= sk
[0];
754 if (!getcwd(buf
, sizeof(buf
)))
756 sendargv(r
, PKTYPE_ARGS
, argv
);
757 sendargv(r
, PKTYPE_ENV
, environ
);
758 pksend(r
, PKTYPE_DIR
, buf
, strlen(buf
) + 1);
759 pksend(r
, PKTYPE_GO
, 0, 0);
762 /* --- Ready to rock'n'roll --- */
767 /* --- Tidy up if it failed --- */
776 /*----- Subcommands -------------------------------------------------------*/
778 /* --- @swrsh_rsh@ --- */
780 void rsw_rsh(sw_remote
*r
, char *argv
[], char *env
[])
786 /* --- Create a pipe --- */
789 swdie(r
, 1, "couldn't create pipe: %s", strerror(errno
));
791 /* --- Start the child process up --- */
795 swdie(r
, 1, "fork failed: %s", strerror(errno
));
799 /* --- Use my new environment --- */
801 environ
= env
; /* Yuk. */
803 /* --- Fiddle with pipe file descriptors --- */
811 /* --- Make sure it doesn't get any input --- */
814 fd
= open("/dev/null", O_RDONLY
);
820 /* --- Run the program --- */
822 execvp(argv
[0], argv
);
823 die(1, "couldn't exec `%s': %s", argv
[0], strerror(errno
));
826 /* --- Read the data from the pipe until it closes --- */
830 ssize_t n
= read(pfd
[0], r
->buf
, sizeof(r
->buf
));
832 swdie(r
, 1, "read error: %s", strerror(errno
));
836 pksend(r
, PKTYPE_DATA
, r
->buf
, n
);
840 /* --- Finally, reap the exit status and pass it on --- */
847 swdie(r
, 1, "error reaping child: %s", strerror(errno
));
852 /* --- @sw_rsh@ --- */
854 int sw_rsh(int argc
, char *argv
[])
860 /* --- Check the arguments --- */
863 die(1, "Usage: rsh HOST|ARCH COMMAND [ARGS...]");
865 /* --- Translate architecture names into hostnames --- */
867 if (strcmp(argv
[1], "-") == 0)
870 archent
*a
= arch_lookup(argv
[1], 0);
873 else if (a
->flags
& archFlag_home
)
879 /* --- Start the remote process --- */
881 if (swrsh(&r
, h
, "rsh", argv
+ 2))
882 die(1, "remote shell failed: %s", strerror(errno
));
884 /* --- Cope with packets from the remote process --- */
891 die(1, "error reading packet: %s", strerror(errno
));
893 write(STDOUT_FILENO
, r
.buf
, r
.sz
);
899 moan("command exited due to signal: %s", r
.buf
);
902 moan("command exited with status %i", r
.buf
[0]);
906 moan("command exited unexpectedly");
909 die(1, "unexpected packet type");
913 /* --- Finished --- */
920 /*----- That's all, folks -------------------------------------------------*/