3 * $Id: sw_rsh.c,v 1.5 1999/06/24 16:02:22 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.5 1999/06/24 16:02:22 mdw
33 * Fix signal handling some more.
35 * Revision 1.4 1999/06/24 15:51:17 mdw
36 * Fix signal handlers so they don't corrupt `errno'.
38 * Revision 1.3 1999/06/18 18:58:54 mdw
39 * Signal handling fixes.
41 * Revision 1.2 1999/06/02 17:03:29 mdw
42 * Fix use of `octet' now that mLib includes `bits.h' (as of version 1.3.5
43 * release). Also use the mLib load and store macros rather than doing it
46 * Revision 1.1.1.1 1999/06/02 16:53:34 mdw
51 /*----- Header files ------------------------------------------------------*/
63 #include <sys/types.h>
68 #include <sys/socket.h>
72 extern char **environ
;
75 #include <mLib/alloc.h>
76 #include <mLib/bits.h>
77 #include <mLib/dstr.h>
79 #include <mLib/mdwopt.h>
80 #include <mLib/quis.h>
81 #include <mLib/report.h>
90 /*----- Data structures ---------------------------------------------------*/
94 typedef struct pkhead
{
99 /*----- Static variables --------------------------------------------------*/
101 static int handler
= 0;
102 static rcmd
*rcmds
= RCMD_LINK
;
104 /*----- Packet interface --------------------------------------------------*/
106 /* --- @pksend@ --- *
108 * Arguments: @sw_remote@ = pointer to the remote block
109 * @int type@ = packet type to send
110 * @const void *p@ = pointer to packet data
111 * @size_t sz@ = size of data to send
113 * Returns: Zero if it worked, nonzero otherwise.
115 * Use: Sends a data packet. If the type is `data', then `sz' may be
116 * arbitrarily large and is divided into small eenough chunks.
117 * Otherwise it's an error to send a packet that's too big.
120 int pksend(sw_remote
*r
, int type
, const void *p
, size_t sz
)
126 /* --- Sort out error conditions --- */
128 if (sz
> PKMAX
&& type
!= PKTYPE_DATA
) {
133 /* --- Main output loop --- */
138 /* --- Set up the packet header --- */
140 chunk
= (sz
> PKMAX ? PKMAX
: sz
);
141 STORE16(h
.len
, chunk
);
143 /* --- Write the packet header --- */
146 if (write(r
->fdout
, &h
, PKHEADSZ
) < PKHEADSZ
) {
152 /* --- Write the payload, if there is one --- *
154 * Maybe the OS won't want to bite it all off in one go.
158 ssize_t n
= write(r
->fdout
, q
, chunk
);
159 if (n
< 0 && errno
!= EINTR
)
174 /* --- @pkrecv@ --- *
176 * Arguments: @sw_remote *r@ = remote block
178 * Returns: Packet type received, or @-1@ for an error.
180 * Use: Receives a packet from the remote host. The packet data is
181 * placed in the block's buffer, the block's packet length is
182 * diddled appropriately.
185 int pkrecv(sw_remote
*r
)
192 /* --- Read the packet header --- */
197 n
= read(r
->fdin
, p
, sz
);
198 if (n
< 0 && errno
!= EINTR
)
208 /* --- Hack for error messages --- *
210 * If it doesn't look like a valid packet, read a `chunk' and pretend it's
211 * data. This isn't too bad, because all the packet types are control
212 * codes, and are unlikely to be in a textual message.
214 * Normally what happens here is that something sitting before the `sw'
215 * program fails, reports a plain textual error, and exits. Grabbing the
216 * `last gasp' like this, then, traps that error message and allows
217 * something to report it. The rest ought to be completely silent, so I
218 * get an `unexpected eof' and then drop everything.
220 * This is certainly better than the behaviour otherwise, which is an
221 * @E2BIG@ message reported when the packet size is really ASCII
225 if (h
.type
>= PKTYPE_BOGUS
) {
226 memcpy(r
->buf
, &h
, PKHEADSZ
);
227 n
= read(r
->fdin
, r
->buf
+ PKHEADSZ
, sizeof(r
->buf
) - PKHEADSZ
);
230 r
->sz
= n
+ PKHEADSZ
;
231 return (PKTYPE_DATA
);
234 /* --- Sort out what's going on --- */
245 /* --- Read the packet payload --- */
249 n
= read(r
->fdin
, p
, sz
);
250 if (n
< 0 && errno
!= EINTR
)
263 /*----- Error reporting and exit statuses --------------------------------*/
265 /* --- @swexit@ --- *
267 * Arguments: @sw_remote *r@ = remote context
268 * @int status@ = exit status to return
272 * Use: Reports the exit status via packet protocol and quits.
275 void swexit(sw_remote
*r
, int status
)
277 unsigned char s
= status
;
278 pksend(r
, PKTYPE_STATUS
, &s
, 1);
282 /* --- @swsignal@ --- *
284 * Arguments: @sw_remote *r@ = remote context
285 * @int sig@ = signal ocurrence to return
289 * Use: Reports a signalled-to-death status via packet protocol and
293 void swsignal(sw_remote
*r
, int sig
)
295 #if defined(HAVE_STRSIGNAL)
296 char *s
= strsignal(sig
);
297 #elif defined(HAVE__SYS_SIGLIST)
298 char *s
= _sys_siglist
[sig
];
301 sprintf(s
, "signal %i", sig
);
304 pksend(r
, PKTYPE_STATUS
, s
, strlen(s
) + 1);
308 /* --- @swwait@ --- *
310 * Arguments: @sw_remote *r@ = remote context
311 * @int status@ = status answer from @wait@(2)
315 * Use: Reports a child's demise appropriately, and quits.
318 void swwait(sw_remote
*r
, int status
)
320 if (WIFEXITED(status
))
321 swexit(r
, WEXITSTATUS(status
));
322 else if (WIFSIGNALED(status
))
323 swsignal(r
, WTERMSIG(status
));
328 /* --- @swvprintf@ --- *
330 * Arguments: @sw_remote *r@ = remote context
331 * @const char *format@ = format string
332 * @va_list ap@ = things to format
336 * Use: Writes a string to the remote end. This is the low-level bit
340 void swvprintf(sw_remote
*r
, const char *format
, va_list ap
)
343 dstr_vputf(&d
, format
, ap
);
344 pksend(r
, PKTYPE_DATA
, d
.buf
, d
.len
);
348 /* --- @swprintf@ --- *
350 * Arguments: @sw_remote *r@ = remote context
351 * @const char *format@ = format string
352 * @...@ = other arguments
356 * Use: Writes a string to the remote end.
359 void swprintf(sw_remote
*r
, const char *format
, ...)
362 va_start(ap
, format
);
363 swvprintf(r
, format
, ap
);
369 * Arguments: @sw_remote *r@ = remote context
370 * @int status@ = exit status to report
371 * @const char *format@ = format string to fill in
372 * @...@ = other arguments
376 * Use: Reports a message and quits.
379 void swdie(sw_remote
*r
, int status
, const char *format
, ...)
384 va_start(ap
, format
);
385 dstr_putf(&d
, "%s [remote]: ", QUIS
);
386 dstr_vputf(&d
, format
, ap
);
390 pksend(r
, PKTYPE_DATA
, d
.buf
, d
.len
);
395 /*----- Command handling and dispatch -------------------------------------*/
397 /* --- @remote@ --- *
399 * Arguments: @sw_remote *r@ = pointer to remote block
400 * @const char *cmd@ = command to run
401 * @char *argv[]@ = argument array
402 * @char *env[]@ = environment variables
404 * Returns: Doesn't. Reports an exit status through packet protocol and
407 * Use: Dispatches a remote command. At this point, the two code
408 * paths for local and remote invokation have joined again.
411 static void remote(sw_remote
*r
, const char *cmd
, char *argv
[], char *env
[])
413 struct rcmd
*p
, *chosen
= 0;
414 size_t sz
= strlen(cmd
);
416 /* --- Make sure that I can get the exit status of children --- */
418 signal(SIGCHLD
, SIG_DFL
);
420 /* --- Fix up the environment --- */
426 if (env
!= environ
) {
428 env_import(&t
, environ
);
430 env_put(&t
, "SW_ARCH", ARCH
);
431 env_file(&t
, DATADIR
"/sw-env");
432 env
= env_export(&t
);
435 /* --- Dispatch to the command handler --- */
437 for (p
= rcmds
; p
; p
= p
->next
) {
438 if (strncmp(cmd
, p
->name
, sz
) == 0) {
439 if (p
->name
[sz
] == 0) {
443 swdie(r
, 1, "ambiguous remote command name `%s'", cmd
);
449 swdie(r
, 1, "unknown remote command name `%s'", cmd
);
450 chosen
->rcmd(r
, argv
, env
);
453 /*----- Remote invocation -------------------------------------------------*/
455 /* --- @sendargv@ --- *
457 * Arguments: @sw_remote *r@ = pointer to the remote context
458 * @int type@ = packet type to send with
459 * @char *v[]@ = pointer to the array to send
461 * Returns: Zero if OK, nonzero if it failed.
463 * Use: Sends something @argv@-shaped; i.e., an array of strings
464 * terminated by a null pointer.
467 static int sendargv(sw_remote
*r
, int type
, char *v
[])
474 d
.len
++; /* Make the null `real' */
477 e
= pksend(r
, type
, d
.buf
, d
.len
);
482 /* --- @snarfargv@ --- *
484 * Arguments: @const char *buf@ = pointer to buffer
485 * @size_t sz@ = size of buffer
487 * Returns: Pointer to argument array (allocated with @malloc@).
489 * Use: Snarfs the null-terminated strings in the buffer and returns
490 * an array of them. The whole lot, strings and array, is
491 * returned in one big chunk allocated from the heap. Note that
492 * this means it's OK to throw the initial buffer away.
495 static char **snarfargv(const char *buf
, size_t sz
)
497 /* --- Initial setup --- */
504 /* --- Pass one: count the number of arguments --- */
520 /* --- Allocate memory for everything --- */
522 v
= xmalloc((c
+ 1) * sizeof(char *) + sz
+ 1);
523 q
= (char *)(v
+ c
+ 1);
526 /* --- Pass two: set up the arrays --- */
548 /* --- @swrsh_remote@ --- *
550 * Arguments: @const char *cmd@ = the command to perform
552 * Returns: Doesn't. Reports an exit status through packet protocol and
555 * Use: Handles the remote end of a remote job invokation.
558 void swrsh_remote(const char *cmd
)
561 static char *dummy
= 0;
568 /* --- Read packets from the remote host --- */
574 swdie(&r
, 1, "error reading packet: %s", strerror(errno
));
581 argv
= snarfargv(r
.buf
, r
.sz
);
586 env
= snarfargv(r
.buf
, r
.sz
);
592 dir
= xstrdup(r
.buf
);
598 swdie(&r
, 1, "internal error: unexpected packet");
603 /* --- Sort out any missing arguments --- */
613 /* --- Run the command --- */
616 remote(&r
, cmd
, argv
, env
);
617 CATCH
switch (exc_type
) {
619 static char msg
[] = "\nsw [remote]: not enough memory\n";
620 pksend(&r
, PKTYPE_DATA
, msg
, sizeof(msg
) - 1);
624 swdie(&r
, 1, "uncaught exception, type = %lx", exc_type
);
628 /*----- Starting remote jobs ----------------------------------------------*/
630 /* --- @sigchld@ --- *
632 * Arguments: @int sig@ = the signal number
636 * Use: Catches @SIGCHLD@ and reaps any children that have lost.
639 static void sigchld(int sig
)
644 while (waitpid(-1, &status
, WNOHANG
) > 0) {
645 if (WIFEXITED(status
)) {
646 fprintf(stderr
, "reap child with exit status %i\n",
647 WEXITSTATUS(status
));
648 } else if (WIFSIGNALED(status
)) {
649 fprintf(stderr
, "reap child killed by signal %s\n",
650 strsignal(WTERMSIG(status
)));
652 fprintf(stderr
, "reaped bizarre child which is still alive\n");
655 while (waitpid(-1, 0, WNOHANG
) > 0)
663 * Arguments: @sw_remote *r@ = remote process block to look after
664 * @const char *host@ = host to run on (0 for this one)
665 * @const char *cmd@ = remote command to run
666 * @char *argv[]@ = arguments to pass on
668 * Returns: Zero if it worked, nonzero if not.
670 * Use: Runs a command on a remote host. The argument array is
671 * mangled to come out OK at the far end. The environment and
672 * current directory are also passed along, and pop out the
673 * other end unmolested.
676 int swrsh(sw_remote
*r
, const char *host
, const char *cmd
, char *argv
[])
681 /* --- Get a socket pair for communicating with the other end --- */
683 if (socketpair(PF_UNIX
, SOCK_STREAM
, 0, sk
))
686 /* --- Set up a signal handler --- */
690 sa
.sa_handler
= sigchld
;
691 sa
.sa_flags
= SA_NOCLDSTOP
;
693 sa
.sa_flags
|= SA_RESTART
;
695 sigemptyset(&sa
.sa_mask
);
696 sigaction(SIGCHLD
, &sa
, 0);
700 /* --- Fork off a child to cope with stuff --- */
706 /* --- Handle the child process --- *
708 * If this is a local job, then just loop around inside to handle the
709 * `remote' command. Otherwise crank up `rsh' and pass the command over to
710 * a remote copy of myself.
712 * (Why do I need a separate process for local jobs? I don't really, but
713 * it makes everything much simpler when running multiple jobs at the same
720 /* --- Child end of a local job --- */
722 signal(SIGINT
, SIG_DFL
);
723 signal(SIGQUIT
, SIG_DFL
);
726 r
->fdin
= r
->fdout
= sk
[1];
727 remote(r
, cmd
, argv
, environ
);
730 /* --- Local child end of a remote job --- */
739 rsh
= getenv("SW_RSH");
742 execlp(rsh
, rsh
, host
, PATH_SW
, "--remote", cmd
, (char *)0);
745 /* --- I don't expect either to come back --- */
750 /* --- Local sort out of what to do --- *
752 * Either way, I've now got a socket tied to something which speaks my
753 * communication protocol. However, if this is a local job, then I can get
754 * going right away; otherwise, I've got to transmit various bits of
755 * information over the protocol.
758 r
->fdin
= r
->fdout
= sk
[0];
763 if (!getcwd(buf
, sizeof(buf
)))
765 sendargv(r
, PKTYPE_ARGS
, argv
);
766 sendargv(r
, PKTYPE_ENV
, environ
);
767 pksend(r
, PKTYPE_DIR
, buf
, strlen(buf
) + 1);
768 pksend(r
, PKTYPE_GO
, 0, 0);
771 /* --- Ready to rock'n'roll --- */
776 /* --- Tidy up if it failed --- */
785 /*----- Subcommands -------------------------------------------------------*/
787 /* --- @swrsh_rsh@ --- */
789 void rsw_rsh(sw_remote
*r
, char *argv
[], char *env
[])
795 /* --- Create a pipe --- */
798 swdie(r
, 1, "couldn't create pipe: %s", strerror(errno
));
800 /* --- Start the child process up --- */
804 swdie(r
, 1, "fork failed: %s", strerror(errno
));
808 /* --- Use my new environment --- */
810 environ
= env
; /* Yuk. */
812 /* --- Fiddle with pipe file descriptors --- */
820 /* --- Make sure it doesn't get any input --- */
823 fd
= open("/dev/null", O_RDONLY
);
829 /* --- Run the program --- */
831 execvp(argv
[0], argv
);
832 die(1, "couldn't exec `%s': %s", argv
[0], strerror(errno
));
835 /* --- Read the data from the pipe until it closes --- */
839 ssize_t n
= read(pfd
[0], r
->buf
, sizeof(r
->buf
));
841 swdie(r
, 1, "read error: %s", strerror(errno
));
845 pksend(r
, PKTYPE_DATA
, r
->buf
, n
);
849 /* --- Finally, reap the exit status and pass it on --- */
856 swdie(r
, 1, "error reaping child: %s", strerror(errno
));
861 /* --- @sw_rsh@ --- */
863 int sw_rsh(int argc
, char *argv
[])
869 /* --- Check the arguments --- */
872 die(1, "Usage: rsh HOST|ARCH COMMAND [ARGS...]");
874 /* --- Translate architecture names into hostnames --- */
876 if (strcmp(argv
[1], "-") == 0)
879 archent
*a
= arch_lookup(argv
[1], 0);
882 else if (a
->flags
& archFlag_home
)
888 /* --- Start the remote process --- */
890 if (swrsh(&r
, h
, "rsh", argv
+ 2))
891 die(1, "remote shell failed: %s", strerror(errno
));
893 /* --- Cope with packets from the remote process --- */
900 die(1, "error reading packet: %s", strerror(errno
));
902 write(STDOUT_FILENO
, r
.buf
, r
.sz
);
908 moan("command exited due to signal: %s", r
.buf
);
911 moan("command exited with status %i", r
.buf
[0]);
915 moan("command exited unexpectedly");
918 die(1, "unexpected packet type");
922 /* --- Finished --- */
929 /*----- That's all, folks -------------------------------------------------*/