summaryrefslogtreecommitdiff
path: root/conmux/conmux-attach
blob: 695d9ff8a1414fa80dc04233b2df8891d7b86533 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#!/usr/bin/perl
#
# conmux-attach -- attach commands to the console
#
# Attach stand alone commands to a console stream.  You can specify
# which of the commands file descriptors are connected to which of the
# 'steams' in the multiplexor; the console input/output and the user
# output.
#
# (C) Copyright IBM Corp. 2004, 2005, 2006
# Author: Andy Whitcroft <andyw@uk.ibm.com>
#
# The Console Multiplexor is released under the GNU Public License V2
#
use FindBin;
use IO::Socket;
use Getopt::Long qw(:config no_auto_abbrev);

# Find our internal libraries.
use lib $FindBin::Bin;
use Conmux;

my $P = 'conmux-attach';
my ($in, $out, $err);

# Usage.
GetOptions(
	'i|stdout=s'	=> \$in,
	'o|stdin=s'	=> \$out,
	'e|stderr=s'	=> \$err,
	'b|bot=s'	=> \$bot,
) or exit;

if ($in eq '' && $out eq '' && $err eq '') {
	$in = 'client';
	$out = 'client';
}

if ($#ARGV < 1) {
	print STDERR "$P: <host:port> <program> ...\n";
	exit 1;
}
my ($mux, $app) = @ARGV;
shift;
$app =~ s@.*/@@; $app =~ s@\s.*$@@;
$app = $bot if ($bot);

#
# Connect to the client channel.
#
sub conmux_connect {
	my ($mux, $type) = @_;

	if (!$cache{$mux, $type}) {
		my $con = Conmux::connect($mux);
		my %r = Conmux::sendCmd($con, 'CONNECT', {
				'id' => 'bot:' . $app, 
				'to' => 'console',
				'type' => $type } );
		die "$P: $mux: connect failed - $r{'status'}\n"
			if ($r{'status'} ne "OK");

		$cache{$mux, $type} = $con;
	}

	$cache{$mux, $type};
}

if ($in) {
	my $to = conmux_connect($mux, $in);
	open(STDIN, "<&", $to) ||
		die "$P: unable to hand off socket to stdin - $!\n";
}
if ($out) {
	my $to = conmux_connect($mux, $out);
	open(STDOUT, ">&", $to) ||
		die "$P: unable to hand off socket to stdout - $!\n";
}
if ($err) {
	my $to = conmux_connect($mux, $err);
	open(STDERR, ">&", $to) ||
		die "$P: unable to hand off socket to stderr - $!\n";
}
exec @ARGV;