summaryrefslogtreecommitdiffstats
path: root/lib/App/Termcast.pm
blob: 75613aa5c2f277bb4f5912bdbcea2a9e120270f5 (plain) (blame)
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
package App::Termcast;
use Moose;
# ABSTRACT: broadcast your terminal sessions for remote viewing

with 'MooseX::Getopt::Dashes';

use IO::Select;
use IO::Socket::INET;
use JSON;
use Scalar::Util 'weaken';
use Term::Filter;
use Term::ReadKey;
use Try::Tiny;

=head1 SYNOPSIS

  my $tc = App::Termcast->new(user => 'foo');
  $tc->run('bash');

=head1 DESCRIPTION

App::Termcast is a client for the L<http://termcast.org/> service, which allows
broadcasting of a terminal session for remote viewing.

=cut

=attr host

Server to connect to (defaults to noway.ratry.ru, the host for the termcast.org
service).

=cut

has host => (
    is      => 'rw',
    isa     => 'Str',
    default => 'noway.ratry.ru',
    documentation => 'Hostname of the termcast server to connect to',
);

=attr port

Port to use on the termcast server (defaults to 31337).

=cut

has port => (
    is      => 'rw',
    isa     => 'Int',
    default => 31337,
    documentation => 'Port to connect to on the termcast server',
);

=attr user

Username to use (defaults to the local username).

=cut

has user => (
    is      => 'rw',
    isa     => 'Str',
    default => sub { $ENV{USER} },
    documentation => 'Username for the termcast server',
);

=attr password

Password for the given user. The password is set the first time that username
connects, and must be the same every subsequent time. It is sent in plaintext
as part of the connection process, so don't use an important password here.
Defaults to 'asdf' since really, a password isn't all that important unless
you're worried about being impersonated.

=cut

has password => (
    is      => 'rw',
    isa     => 'Str',
    default => 'asdf', # really unimportant
    documentation => "Password for the termcast server\n"
                   . "                              (mostly unimportant)",
);

=attr bell_on_watcher

Whether or not to send a bell to the terminal when a watcher connects or
disconnects. Defaults to false.

=cut

has bell_on_watcher => (
    is      => 'rw',
    isa     => 'Bool',
    default => 0,
    documentation => "Send a terminal bell when a watcher connects\n"
                   . "                              or disconnects",
);

=attr timeout

How long in seconds to use for the timeout to the termcast server. Defaults to
5.

=cut

has timeout => (
    is      => 'rw',
    isa     => 'Int',
    default => 5,
    documentation => "Timeout length for the connection to the termcast server",
);

=method establishment_message

Returns the string sent to the termcast server when connecting (typically
containing the username and password)

=cut

has establishment_message => (
    traits     => ['NoGetopt'],
    is         => 'ro',
    isa        => 'Str',
    lazy_build => 1,
);

sub _build_establishment_message {
    my $self = shift;
    return sprintf("hello %s %s\n", $self->user, $self->password);
}

sub _termsize {
    return try { GetTerminalSize() } catch { (undef, undef) };
}

=method termsize_message

Returns the string sent to the termcast server whenever the terminal size
changes.

=cut

sub termsize_message {
    my $self = shift;

    my ($cols, $lines) = $self->_termsize;

    return '' unless $cols && $lines;

    return $self->_form_metadata_string(
        geometry => [ $cols, $lines ],
    );
}

has socket => (
    traits     => ['NoGetopt'],
    is         => 'rw',
    isa        => 'IO::Socket::INET',
    lazy_build => 1,
    init_arg   => undef,
);

sub _form_metadata_string {
    my $self = shift;
    my %data = @_;

    my $json = JSON::encode_json(\%data);

    return "\e[H\x00$json\xff\e[H\e[2J";
}

sub _build_socket {
    my $self = shift;

    my $socket;
    {
        $socket = IO::Socket::INET->new(PeerAddr => $self->host,
                                        PeerPort => $self->port);
        if (!$socket) {
            Carp::carp "Couldn't connect to " . $self->host . ": $!";
            ReadMode 0 if $self->_has_term && $self->_term->_raw_mode;
            sleep 5;
            ReadMode 5 if $self->_has_term && $self->_term->_raw_mode;
            redo;
        }
    }

    syswrite $socket, $self->establishment_message . $self->termsize_message;

    # ensure the server accepted our connection info
    {
        my $select = IO::Select->new($socket);
        my ($r, undef, $e) = IO::Select->select(
            $select, undef, $select,
        );

        for my $fh (@$e) {
            if ($fh == $socket) {
                ReadMode 0 if $self->_has_term && $self->_term->_raw_mode;
                Carp::croak("Invalid password");
            }
        }
        for my $fh (@$r) {
            if ($fh == $socket) {
                my $buf;
                $socket->recv($buf, 4096);
                if (!defined $buf || length $buf == 0) {
                    ReadMode 0 if $self->_has_term && $self->_term->_raw_mode;
                    Carp::croak("Invalid password");
                }
                elsif ($buf ne ('hello, ' . $self->user . "\n")) {
                    ReadMode 0 if $self->_has_term && $self->_term->_raw_mode;
                    Carp::carp("Unknown login response from server: $buf");
                    ReadMode 5 if $self->_has_term && $self->_term->_raw_mode;
                }
            }
        }
    }

    ReadMode 5 if $self->_has_term && $self->_term->_raw_mode;
    return $socket;
}

before clear_socket => sub {
    my $self = shift;
    Carp::carp("Lost connection to server ($!), reconnecting...");
    ReadMode 0 if $self->_has_term && $self->_term->_raw_mode;
};

sub _new_socket {
    my $self = shift;
    $self->clear_socket;
    $self->socket;
}

has _needs_termsize_update => (
    traits  => ['NoGetopt'],
    is      => 'rw',
    isa     => 'Bool',
    default => 0,
);

has _term => (
    is        => 'ro',
    isa       => 'Term::Filter',
    lazy      => 1,
    predicate => '_has_term',
    default   => sub {
        my $_self = shift;
        weaken(my $self = $_self);
        Term::Filter->new(
            callbacks => {
                setup => sub {
                    my ($term) = @_;
                    $term->add_input_handle($self->socket);
                },
                winch => sub {
                    # for the sake of sending a clear to the client anyway
                    syswrite $self->output, "\e[H\e[2J";
                    $self->_needs_termsize_update(1);
                },
                read_error => sub {
                    my ($term, $fh) = @_;
                    if ($fh == $self->socket) {
                        $self->_new_socket;
                    }
                },
                read => sub {
                    my ($term, $fh) = @_;
                    if ($fh == $self->socket) {
                        my $got = $term->_read_from_handle(
                            $self->socket, "socket"
                        );
                        $self->_new_socket unless defined $got;

                        if ($self->bell_on_watcher) {
                            # something better to do here?
                            syswrite $self->output, "\a";
                        }
                    }
                },
                munge_output => sub {
                    my ($term, $buf) = @_;
                    $self->write_to_termcast($buf);
                    $buf;
                },
            },
        );
    },
    handles => [ 'run', 'input', 'output' ],
);

=method write_to_termcast $BUF

Sends C<$BUF> to the termcast server.

=cut

sub write_to_termcast {
    my $self = shift;
    my ($buf) = @_;

    my $socket = $self->socket;
    my $select = IO::Select->new($socket);

    my (undef, $w, $e) = IO::Select->select(
        undef, $select, $select, $self->timeout,
    );

    my $err;

    for my $fh (@$e) {
        if ($fh == $socket) {
            $err = 1;
        }
    }

    if (!$err) {
        for my $fh (@$w) {
            if ($fh == $socket) {
                if ($self->_needs_termsize_update) {
                    $buf = $self->termsize_message . $buf;
                    $self->_needs_termsize_update(0);
                }

                return $self->socket->syswrite($buf);
            }
        }
    }

    $self->clear_socket;
    return $self->write_to_termcast(@_);
}

=method run @ARGV

Runs the given command in the local terminal as though via C<system>, but
streams all output from that command to the termcast server. The command may be
an interactive program (in fact, this is the most useful case).

=cut

__PACKAGE__->meta->make_immutable;
no Moose;

=head1 TODO

Use L<MooseX::SimpleConfig> to make configuration easier.

=head1 BUGS

No known bugs.

Please report any bugs through RT: email
C<bug-app-termcast at rt.cpan.org>, or browse to
L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=App-Termcast>.

=head1 SEE ALSO

L<http://termcast.org/>

=head1 SUPPORT

You can find this documentation for this module with the perldoc command.

    perldoc App::Termcast

You can also look for information at:

=over 4

=item * AnnoCPAN: Annotated CPAN documentation

L<http://annocpan.org/dist/App-Termcast>

=item * CPAN Ratings

L<http://cpanratings.perl.org/d/App-Termcast>

=item * RT: CPAN's request tracker

L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=App-Termcast>

=item * Search CPAN

L<http://search.cpan.org/dist/App-Termcast>

=back

=cut

1;