3 * $Id: sw_rsh.c,v 1.2 1999/06/02 17:03:29 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.2 1999/06/02 17:03:29 mdw
33 * Fix use of `octet' now that mLib includes `bits.h' (as of version 1.3.5
34 * release). Also use the mLib load and store macros rather than doing it
37 * Revision 1.1.1.1 1999/06/02 16:53:34 mdw
42 /*----- Header files ------------------------------------------------------*/
54 #include <sys/types.h>
59 #include <sys/socket.h>
63 extern char **environ
;
66 #include <mLib/alloc.h>
67 #include <mLib/bits.h>
68 #include <mLib/dstr.h>
70 #include <mLib/mdwopt.h>
71 #include <mLib/quis.h>
72 #include <mLib/report.h>
81 /*----- Data structures ---------------------------------------------------*/
85 typedef struct pkhead
{
90 /*----- Static variables --------------------------------------------------*/
92 static int handler
= 0;
93 static rcmd
*rcmds
= RCMD_LINK
;
95 /*----- Packet interface --------------------------------------------------*/
99 * Arguments: @sw_remote@ = pointer to the remote block
100 * @int type@ = packet type to send
101 * @const void *p@ = pointer to packet data
102 * @size_t sz@ = size of data to send
104 * Returns: Zero if it worked, nonzero otherwise.
106 * Use: Sends a data packet. If the type is `data', then `sz' may be
107 * arbitrarily large and is divided into small eenough chunks.
108 * Otherwise it's an error to send a packet that's too big.
111 int pksend(sw_remote
*r
, int type
, const void *p
, size_t sz
)
117 /* --- Sort out error conditions --- */
119 if (sz
> PKMAX
&& type
!= PKTYPE_DATA
) {
124 /* --- Main output loop --- */
129 /* --- Set up the packet header --- */
131 chunk
= (sz
> PKMAX ? PKMAX
: sz
);
132 STORE16(h
.len
, chunk
);
134 /* --- Write the packet header --- */
137 if (write(r
->fdout
, &h
, PKHEADSZ
) < PKHEADSZ
) {
143 /* --- Write the payload, if there is one --- *
145 * Maybe the OS won't want to bite it all off in one go.
149 ssize_t n
= write(r
->fdout
, q
, chunk
);
150 if (n
< 0 && errno
!= EINTR
)
165 /* --- @pkrecv@ --- *
167 * Arguments: @sw_remote *r@ = remote block
169 * Returns: Packet type received, or @-1@ for an error.
171 * Use: Receives a packet from the remote host. The packet data is
172 * placed in the block's buffer, the block's packet length is
173 * diddled appropriately.
176 int pkrecv(sw_remote
*r
)
183 /* --- Read the packet header --- */
188 n
= read(r
->fdin
, p
, sz
);
189 if (n
< 0 && errno
!= EINTR
)
199 /* --- Hack for error messages --- *
201 * If it doesn't look like a valid packet, read a `chunk' and pretend it's
202 * data. This isn't too bad, because all the packet types are control
203 * codes, and are unlikely to be in a textual message.
205 * Normally what happens here is that something sitting before the `sw'
206 * program fails, reports a plain textual error, and exits. Grabbing the
207 * `last gasp' like this, then, traps that error message and allows
208 * something to report it. The rest ought to be completely silent, so I
209 * get an `unexpected eof' and then drop everything.
211 * This is certainly better than the behaviour otherwise, which is an
212 * @E2BIG@ message reported when the packet size is really ASCII
216 if (h
.type
>= PKTYPE_BOGUS
) {
217 memcpy(r
->buf
, &h
, PKHEADSZ
);
218 n
= read(r
->fdin
, r
->buf
+ PKHEADSZ
, sizeof(r
->buf
) - PKHEADSZ
);
221 r
->sz
= n
+ PKHEADSZ
;
222 return (PKTYPE_DATA
);
225 /* --- Sort out what's going on --- */
236 /* --- Read the packet payload --- */
240 n
= read(r
->fdin
, p
, sz
);
241 if (n
< 0 && errno
!= EINTR
)
254 /*----- Error reporting and exit statuses --------------------------------*/
256 /* --- @swexit@ --- *
258 * Arguments: @sw_remote *r@ = remote context
259 * @int status@ = exit status to return
263 * Use: Reports the exit status via packet protocol and quits.
266 void swexit(sw_remote
*r
, int status
)
268 unsigned char s
= status
;
269 pksend(r
, PKTYPE_STATUS
, &s
, 1);
273 /* --- @swsignal@ --- *
275 * Arguments: @sw_remote *r@ = remote context
276 * @int sig@ = signal ocurrence to return
280 * Use: Reports a signalled-to-death status via packet protocol and
284 void swsignal(sw_remote
*r
, int sig
)
286 #if defined(HAVE_STRSIGNAL)
287 char *s
= strsignal(sig
);
288 #elif defined(HAVE__SYS_SIGLIST)
289 char *s
= _sys_siglist
[sig
];
292 sprintf(s
, "signal %i", sig
);
295 pksend(r
, PKTYPE_STATUS
, s
, strlen(s
) + 1);
299 /* --- @swwait@ --- *
301 * Arguments: @sw_remote *r@ = remote context
302 * @int status@ = status answer from @wait@(2)
306 * Use: Reports a child's demise appropriately, and quits.
309 void swwait(sw_remote
*r
, int status
)
311 if (WIFEXITED(status
))
312 swexit(r
, WEXITSTATUS(status
));
313 else if (WIFSIGNALED(status
))
314 swsignal(r
, WTERMSIG(status
));
319 /* --- @swvprintf@ --- *
321 * Arguments: @sw_remote *r@ = remote context
322 * @const char *format@ = format string
323 * @va_list ap@ = things to format
327 * Use: Writes a string to the remote end. This is the low-level bit
331 void swvprintf(sw_remote
*r
, const char *format
, va_list ap
)
334 dstr_vputf(&d
, format
, ap
);
335 pksend(r
, PKTYPE_DATA
, d
.buf
, d
.len
);
339 /* --- @swprintf@ --- *
341 * Arguments: @sw_remote *r@ = remote context
342 * @const char *format@ = format string
343 * @...@ = other arguments
347 * Use: Writes a string to the remote end.
350 void swprintf(sw_remote
*r
, const char *format
, ...)
353 va_start(ap
, format
);
354 swvprintf(r
, format
, ap
);
360 * Arguments: @sw_remote *r@ = remote context
361 * @int status@ = exit status to report
362 * @const char *format@ = format string to fill in
363 * @...@ = other arguments
367 * Use: Reports a message and quits.
370 void swdie(sw_remote
*r
, int status
, const char *format
, ...)
375 va_start(ap
, format
);
376 dstr_putf(&d
, "%s [remote]: ", QUIS
);
377 dstr_vputf(&d
, format
, ap
);
381 pksend(r
, PKTYPE_DATA
, d
.buf
, d
.len
);
386 /*----- Command handling and dispatch -------------------------------------*/
388 /* --- @remote@ --- *
390 * Arguments: @sw_remote *r@ = pointer to remote block
391 * @const char *cmd@ = command to run
392 * @char *argv[]@ = argument array
393 * @char *env[]@ = environment variables
395 * Returns: Doesn't. Reports an exit status through packet protocol and
398 * Use: Dispatches a remote command. At this point, the two code
399 * paths for local and remote invokation have joined again.
402 static void remote(sw_remote
*r
, const char *cmd
, char *argv
[], char *env
[])
404 struct rcmd
*p
, *chosen
= 0;
405 size_t sz
= strlen(cmd
);
407 /* --- Make sure that I can get the exit status of children --- */
409 signal(SIGCHLD
, SIG_DFL
);
411 /* --- Fix up the environment --- */
417 if (env
!= environ
) {
419 env_import(&t
, environ
);
421 env_put(&t
, "SW_ARCH", ARCH
);
422 env_file(&t
, DATADIR
"/sw-env");
423 env
= env_export(&t
);
426 /* --- Dispatch to the command handler --- */
428 for (p
= rcmds
; p
; p
= p
->next
) {
429 if (strncmp(cmd
, p
->name
, sz
) == 0) {
430 if (p
->name
[sz
] == 0) {
434 swdie(r
, 1, "ambiguous remote command name `%s'", cmd
);
440 swdie(r
, 1, "unknown remote command name `%s'", cmd
);
441 chosen
->rcmd(r
, argv
, env
);
444 /*----- Remote invocation -------------------------------------------------*/
446 /* --- @sendargv@ --- *
448 * Arguments: @sw_remote *r@ = pointer to the remote context
449 * @int type@ = packet type to send with
450 * @char *v[]@ = pointer to the array to send
452 * Returns: Zero if OK, nonzero if it failed.
454 * Use: Sends something @argv@-shaped; i.e., an array of strings
455 * terminated by a null pointer.
458 static int sendargv(sw_remote
*r
, int type
, char *v
[])
465 d
.len
++; /* Make the null `real' */
468 e
= pksend(r
, type
, d
.buf
, d
.len
);
473 /* --- @snarfargv@ --- *
475 * Arguments: @const char *buf@ = pointer to buffer
476 * @size_t sz@ = size of buffer
478 * Returns: Pointer to argument array (allocated with @malloc@).
480 * Use: Snarfs the null-terminated strings in the buffer and returns
481 * an array of them. The whole lot, strings and array, is
482 * returned in one big chunk allocated from the heap. Note that
483 * this means it's OK to throw the initial buffer away.
486 static char **snarfargv(const char *buf
, size_t sz
)
488 /* --- Initial setup --- */
495 /* --- Pass one: count the number of arguments --- */
511 /* --- Allocate memory for everything --- */
513 v
= xmalloc((c
+ 1) * sizeof(char *) + sz
+ 1);
514 q
= (char *)(v
+ c
+ 1);
517 /* --- Pass two: set up the arrays --- */
539 /* --- @swrsh_remote@ --- *
541 * Arguments: @const char *cmd@ = the command to perform
543 * Returns: Doesn't. Reports an exit status through packet protocol and
546 * Use: Handles the remote end of a remote job invokation.
549 void swrsh_remote(const char *cmd
)
552 static char *dummy
= 0;
559 /* --- Read packets from the remote host --- */
565 swdie(&r
, 1, "error reading packet: %s", strerror(errno
));
572 argv
= snarfargv(r
.buf
, r
.sz
);
577 env
= snarfargv(r
.buf
, r
.sz
);
583 dir
= xstrdup(r
.buf
);
589 swdie(&r
, 1, "internal error: unexpected packet");
594 /* --- Sort out any missing arguments --- */
604 /* --- Run the command --- */
607 remote(&r
, cmd
, argv
, env
);
608 CATCH
switch (exc_type
) {
610 static char msg
[] = "\nsw [remote]: not enough memory\n";
611 pksend(&r
, PKTYPE_DATA
, msg
, sizeof(msg
) - 1);
615 swdie(&r
, 1, "uncaught exception, type = %lx", exc_type
);
619 /*----- Starting remote jobs ----------------------------------------------*/
621 /* --- @sigchld@ --- *
623 * Arguments: @int sig@ = the signal number
627 * Use: Catches @SIGCHLD@ and reaps any children that have lost.
630 static void sigchld(int sig
)
634 while (waitpid(-1, &status
, WNOHANG
) > 0) {
635 if (WIFEXITED(status
)) {
636 fprintf(stderr
, "reap child with exit status %i\n",
637 WEXITSTATUS(status
));
638 } else if (WIFSIGNALED(status
)) {
639 fprintf(stderr
, "reap child killed by signal %s\n",
640 strsignal(WTERMSIG(status
)));
642 fprintf(stderr
, "reaped bizarre child which is still alive\n");
645 while (waitpid(-1, 0, WNOHANG
) > 0)
652 * Arguments: @sw_remote *r@ = remote process block to look after
653 * @const char *host@ = host to run on (0 for this one)
654 * @const char *cmd@ = remote command to run
655 * @char *argv[]@ = arguments to pass on
657 * Returns: Zero if it worked, nonzero if not.
659 * Use: Runs a command on a remote host. The argument array is
660 * mangled to come out OK at the far end. The environment and
661 * current directory are also passed along, and pop out the
662 * other end unmolested.
665 int swrsh(sw_remote
*r
, const char *host
, const char *cmd
, char *argv
[])
670 /* --- Get a socket pair for communicating with the other end --- */
672 if (socketpair(PF_UNIX
, SOCK_STREAM
, 0, sk
))
675 /* --- Set up a signal handler --- */
679 sa
.sa_handler
= sigchld
;
681 sigemptyset(&sa
.sa_mask
);
682 sigaction(SIGCHLD
, &sa
, 0);
686 /* --- Fork off a child to cope with stuff --- */
692 /* --- Handle the child process --- *
694 * If this is a local job, then just loop around inside to handle the
695 * `remote' command. Otherwise crank up `rsh' and pass the command over to
696 * a remote copy of myself.
698 * (Why do I need a separate process for local jobs? I don't really, but
699 * it makes everything much simpler when running multiple jobs at the same
706 /* --- Child end of a local job --- */
709 r
->fdin
= r
->fdout
= sk
[1];
710 remote(r
, cmd
, argv
, environ
);
713 /* --- Local child end of a remote job --- */
722 rsh
= getenv("SW_RSH");
725 execlp(rsh
, rsh
, host
, PATH_SW
, "--remote", cmd
, (char *)0);
728 /* --- I don't expect either to come back --- */
733 /* --- Local sort out of what to do --- *
735 * Either way, I've now got a socket tied to something which speaks my
736 * communication protocol. However, if this is a local job, then I can get
737 * going right away; otherwise, I've got to transmit various bits of
738 * information over the protocol.
741 r
->fdin
= r
->fdout
= sk
[0];
746 if (!getcwd(buf
, sizeof(buf
)))
748 sendargv(r
, PKTYPE_ARGS
, argv
);
749 sendargv(r
, PKTYPE_ENV
, environ
);
750 pksend(r
, PKTYPE_DIR
, buf
, strlen(buf
) + 1);
751 pksend(r
, PKTYPE_GO
, 0, 0);
754 /* --- Ready to rock'n'roll --- */
759 /* --- Tidy up if it failed --- */
768 /*----- Subcommands -------------------------------------------------------*/
770 /* --- @swrsh_rsh@ --- */
772 void rsw_rsh(sw_remote
*r
, char *argv
[], char *env
[])
778 /* --- Create a pipe --- */
781 swdie(r
, 1, "couldn't create pipe: %s", strerror(errno
));
783 /* --- Start the child process up --- */
787 swdie(r
, 1, "fork failed: %s", strerror(errno
));
791 /* --- Use my new environment --- */
793 environ
= env
; /* Yuk. */
795 /* --- Fiddle with pipe file descriptors --- */
803 /* --- Make sure it doesn't get any input --- */
806 fd
= open("/dev/null", O_RDONLY
);
812 /* --- Run the program --- */
814 execvp(argv
[0], argv
);
815 die(1, "couldn't exec `%s': %s", argv
[0], strerror(errno
));
818 /* --- Read the data from the pipe until it closes --- */
822 ssize_t n
= read(pfd
[0], r
->buf
, sizeof(r
->buf
));
824 swdie(r
, 1, "read error: %s", strerror(errno
));
828 pksend(r
, PKTYPE_DATA
, r
->buf
, n
);
832 /* --- Finally, reap the exit status and pass it on --- */
839 swdie(r
, 1, "error reaping child: %s", strerror(errno
));
844 /* --- @sw_rsh@ --- */
846 int sw_rsh(int argc
, char *argv
[])
852 /* --- Check the arguments --- */
855 die(1, "Usage: rsh HOST|ARCH COMMAND [ARGS...]");
857 /* --- Translate architecture names into hostnames --- */
859 if (strcmp(argv
[1], "-") == 0)
862 archent
*a
= arch_lookup(argv
[1], 0);
865 else if (a
->flags
& archFlag_home
)
871 /* --- Start the remote process --- */
873 if (swrsh(&r
, h
, "rsh", argv
+ 2))
874 die(1, "remote shell failed: %s", strerror(errno
));
876 /* --- Cope with packets from the remote process --- */
883 die(1, "error reading packet: %s", strerror(errno
));
885 write(STDOUT_FILENO
, r
.buf
, r
.sz
);
891 moan("command exited due to signal: %s", r
.buf
);
894 moan("command exited with status %i", r
.buf
[0]);
898 moan("command exited unexpectedly");
901 die(1, "unexpected packet type");
905 /* --- Finished --- */
912 /*----- That's all, folks -------------------------------------------------*/