-
Notifications
You must be signed in to change notification settings - Fork 0
/
sqar
executable file
·1516 lines (1256 loc) · 47.9 KB
/
sqar
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/perl -w
# qar client/server tool -- Chris Houser, Aron Griffis, April 2001
# $Id: sqar,v 1.23 2002/01/15 23:06:22 chouser Exp $
# TODO:
# add "set screen" to editor statemachine
# handle --batchcmd options on command-line
# check last for linefeed, add one only if needed
# add options to choose server and database
# pool of servers
# test effect of keystrokes during local edit (send and recv)
# vim syntax file
# smarter caching
# invalidate a qar after it has been answered
# link commands "read 1234" and "1234"
# ...etc...
# add "any" option to --serveraddr
# column management?
# hack in use of oldqar?
use strict;
package StreamBuf;
use FileHandle;
sub READ_OK() {0}
sub READ_EOF() {1}
sub READ_BLOCKED() {2}
sub new {
my ($class, $name, $instream, $outstream) = @_;
# init
my $self = {
name => $name,
instream => $instream,
outstream => $outstream || $instream,
buf => '',
lastread => READ_OK,
eol => "\n",
};
bless $self, $class;
# make sure this stream doesn't block the whole server
fcntl($self->{instream}, F_SETFL, O_NONBLOCK) or die;
# return me
return $self;
}
sub seteol {
my ($self, $eol) = @_;
$self->{eol} = $eol;
}
sub fileno {
my ($self, $out) = @_;
return CORE::fileno($self->{outstream}) if $out;
return CORE::fileno($self->{instream});
}
sub readbuf {
my ($self) = @_;
# read a buffer
my $buf;
my $len = sysread $self->{instream}, $buf, 1024;
# update state
if (defined $len) {
if ($len < 1) {
$self->{lastread} = READ_EOF;
}
else {
$self->{lastread} = READ_OK;
$self->{buf} .= $buf;
}
}
elsif ($! == 35) {
$self->{lastread} = READ_BLOCKED;
}
else {
die "Error reading from stream $self->{name}: $!\n";
}
}
sub dataready {
my ($self) = @_;
return $self->{lastread} != READ_BLOCKED;
}
sub lineready {
my ($self) = @_;
return 1 if $self->{buf} =~ /\n/; # whole line
return 1 if $self->{lastread} != READ_OK && $self->{buf}; # partial line
return 1 if $self->{lastread} == READ_EOF; # eof
return 0;
}
sub getline {
my ($self) = @_;
my $rtn;
if ($self->{buf} =~ s/^.*\n//) {
# return a whole line
$rtn = $&;
}
elsif ($self->{lastread} != READ_OK && $self->{buf}) {
# return a partial line
$rtn = $self->{buf};
$self->{buf} = '';
}
elsif ($self->{lastread} == READ_EOF) {
# return EOF
undef $rtn;
}
else {
warn "\nError -- getline should not have been called ($self->{name})\n";
undef $rtn;
}
return $rtn;
}
sub write {
my ($self, $text) = @_;
syswrite $self->{outstream}, $text;
}
sub writeln {
my ($self, $line) = @_;
$self->write("$line" . $self->{eol});
}
package StreamPlex;
sub new {
my ($class, @streams) = @_;
# bless me, I'm a hash
my $self = {};
bless $self, $class;
# init
$self->{streams} = [];
$self->{selectmask} = '';
# add any streams given
for my $stream (@streams) {
$self->addstream($stream);
}
# return me
return $self;
}
sub addstream {
my ($self, $newstream) = @_;
# add new stream to list
push @{$self->{streams}}, $newstream;
# add new stream to selectmask
vec($self->{selectmask}, $newstream->fileno, 1) = 1;
}
sub delstream {
my ($self, $oldstream) = @_;
# remove old stream from selectmask
vec($self->{selectmask}, $oldstream->fileno, 1) = 0;
# find the old stream in my stream list
my @streams;
foreach my $stream (@{$self->{streams}}) {
push @streams, $stream unless $stream == $oldstream;
}
@streams == @{$self->{streams}} && warn "Asked to delete unknown stream\n";
$self->{streams} = \@streams;
}
sub readln {
my ($self) = @_;
die "no streams!\n" unless @{$self->{streams}};
my @dataready = ();
my @lineready = ();
POLLSTREAMS: {
# poll all streams
foreach my $stream (@{$self->{streams}}) {
$stream->readbuf;
push @dataready, $stream if $stream->dataready;
push @lineready, $stream if $stream->lineready;
}
# if all streams are blocking and cacheless, wait for one to be ready
if (! @dataready && ! @lineready) {
my $outbits = $self->{selectmask};
select($outbits, undef, undef, 10);
redo POLLSTREAMS;
}
# we also need to go around again if no lines are ready
redo unless @lineready;
}
# return first cached line from first willing stream
foreach my $stream (@lineready) {
my $line = $stream->getline;
defined $line or $self->delstream($stream); # EOF
return ($stream, $line);
}
# no streams ready? maybe they're all closed
return (undef, undef);
}
package QARSession;
use IPC::Open2;
use FileHandle;
sub new {
my ($class, $debug) = @_;
# bless me, I'm a hash
my $self = {'debug' => $debug};
bless $self, $class;
# default host
$self->{hostname} = "gorge";
# fork off a telnet process
$self->{to} = new FileHandle;
$self->{from} = new FileHandle;
$self->{pid} = open2($self->{from}, $self->{to}, "telnet $self->{hostname}");
# set up streams
$self->{host} = new StreamBuf ('host', $self->{from}, $self->{to});
$self->{plex} = new StreamPlex($self->{host});
$self->{host}->seteol("\r");
# return me
return $self;
}
sub login {
my ($self) = @_;
# get configuration
my $username = $main::config->get('username');
my $password = $main::config->get('password');
my $termtype = $main::config->get('termtype');
defined $username && defined $password
or die "Username and Password are required\n";
my $page = 1;
$self->{state} = 1;
$|=1;
# remap termtype from name to escape sequence
{
$termtype =~ /^LA100$/i and $termtype = "\e[?10;2c" and next;
$termtype =~ /^VT100$/i and $termtype = "\e[?1;2c" and next;
$termtype = eval qq{"$termtype"};
}
my $which;
my $host = $self->{host};
while (($which, $_) = $self->{plex}->readln) {
if ($self->{debug}) {
my $n = $_;
$n =~ s/\r/^M/g;
$n =~ s/\000/^@/g;
print "($n)";
}
/\rUsername: $/ and $host->writeln($username) and next;
/\rPassword: $/ and $host->writeln($password) and next;
/\eZ/ and $host->write($termtype) and next;
/Which QAR database/ and $host->writeln("OSF_QAR") and next;
/QAR> $/ && $page and ($page=0, $host->writeln("nopage")) and next;
/QAR> $/ && !$page and last;
}
$self->{state} = 2;
}
sub docmd {
my ($self, $clientref) = @_;
$self->{state} = 3;
# add client to stream plex
my $clientstream = new StreamBuf('client', $clientref->[0]);
$self->{plex}->addstream($clientstream);
my $interact = 0;
my $cachetemp = '';
my $cachelines = 0;
my $cachekey = '';
my $writeclient = 1;
while (my ($which, $line) = $self->{plex}->readln) {
my $n;
if ($line) {
$n = $line;
$n =~ s/\r/^M/g;
#$n =~ s/\n/^J/g;
$n =~ s/\003/^C/g;
$n =~ s/\032/^Z/g;
$n =~ s/\000/^@/g;
$n =~ s/\033/^[/g;
$n =~ s/[^]?:.;<>[\w\s^-]/'<'.ord($&).'>'/eg;
}
if ($which == $self->{host}) {
return 0 unless $line; # server disconnect
print "{$n}" if $self->{debug};
$line =~ /^QAR> $/ and last;
# escape tildes
$line =~ s/~/~~/g;
$cachetemp .= $line;
$cachelines += 1;
$clientstream->write($line) if $writeclient;
}
else {
return 1 unless $line; # abnormal client disconnect
print "<$n>" if $self->{debug};
$line =~ s/\n/\r/g; # a client \n is a gorge \r
if ($line eq "reload\r") {
main::reload();
last;
}
else {
++$interact;
if ($interact == 1) {
$cachekey = $line;
if (main::isbatchcmd($line)
&& exists $main::cache{$cachekey}) {
$clientstream->write("~cachehit~");
my $entry = $main::cache{$cachekey};
$clientstream->write("~lines:$entry->{lines}~");
$clientstream->write($entry->{data});
# done with client
$writeclient = 0;
$self->{plex}->delstream($clientstream);
undef $clientstream;
undef $clientref->[0];
}
}
$self->{host}->write($line);
}
}
}
$self->{state} = 2;
# done with client
$self->{plex}->delstream($clientstream) if $writeclient;
# update cache if we can
if ($interact == 1 && $cachekey) {
$main::cache{$cachekey} = {
'data' => $cachetemp,
'lines' => $cachelines,
}
}
return 1;
}
package LocalTerm;
use POSIX qw(:termios_h);
sub new {
my ($class) = @_;
# bless me, I'm a hash
my $self = {};
bless $self, $class;
# init
$self->{needsreset} = 0;
# get current term state
$self->{fd} = fileno(STDIN);
$self->{posixterm} = POSIX::Termios->new();
$self->{posixterm}->getattr($self->{fd});
$self->{origflags} = $self->{posixterm}->getlflag();
$self->initsize;
# return me
return $self;
}
sub get {
return $_[0]->{$_[1]};
}
sub initsize {
my ($self) = @_;
# get current term size
my $TIOCGWINSZ;
if ((POSIX::uname)[0] eq 'OSF1') {
# Tru64
$TIOCGWINSZ = 0x40000000 | ((8 & 0x1fff) << 16) | (116 << 8) | 104;
} else {
# Linux
require 'asm/ioctls.ph';
$TIOCGWINSZ = &TIOCGWINSZ;
}
my %vals;
my $winsize = '';
open(TTY, "+</dev/tty") or do{warn "No tty: $!"; return};
ioctl(TTY, $TIOCGWINSZ, $winsize) or do{warn "ioctl TIOCGWINSZ: $!";return};
@vals{'row', 'col', 'xpixel', 'ypixel'} = unpack('S4', $winsize);
%$self = (%$self, %vals);
}
sub setpassthru {
my ($self) = @_;
my $posixterm = $self->{posixterm};
$self->{needsreset} = 1;
$posixterm->setlflag($self->{origflags} & ~(ISIG | ECHO | ECHOK | ICANON));
$posixterm->setcc(VTIME, 1);
$posixterm->setattr($self->{fd}, TCSANOW);
}
sub reset {
my ($self, $always) = @_;
if ($self->{needsreset} || $always) {
my $posixterm = $self->{posixterm};
$posixterm->setlflag($self->{origflags});
$posixterm->setcc(VTIME, 0);
$posixterm->setattr($self->{fd}, TCSANOW);
}
}
sub DESTROY {
my ($self) = @_;
$self->reset;
}
package Config;
use Getopt::Long;
sub new {
my ($class) = @_;
# set default configuration and list of valid config var names
my $self = {
'allowclear' => 0,
'batchcmd' => ['^read', '^\d+', '^dir'], # regexp
'clientport' => undef,
'clientaddr' => 'localhost',
'deltemp' => 1,
'help' => undef,
'listen' => undef,
'mkrc' => undef,
'pageheight' => 'auto',
'password' => undef,
'reload' => undef,
'serveraddr' => 'localhost',
'serverport' => 1357,
'servertimeout' => 60, # minutes
'termtype' => 'VT100',
'uselocaleditor' => 1,
'userescape' => '~',
'username' => undef,
};
$self->{'clientport'} = $self->{'serverport'};
# bless me, I'm a hash
bless $self, $class;
# return me
return $self;
}
sub loadfile {
my ($self, $rcfile) = @_;
$rcfile ||= "$ENV{HOME}/.sqarrc";
return unless -e $rcfile;
$self->{'_rcfile'} = $rcfile;
open F, $rcfile;
while(<F>) {
# skip comments and blank lines
next if /^\s*(#.*)?\s*$/;
# parse line
my ($name, $op, $val) = (/^\s*(\w+)-?(\w*)\s+(.*?)\s*$/);
$name or warn "Error parsing $rcfile, line $.\n" and next;
$name = lc $name;
$op = lc $op;
# handle quoted values
$val =~ s/^"(.*)"$/$1/;
# check for valid config variable
unless (exists $self->{$name}) {
warn "Unknown config option in $rcfile line $.: $_\n";
next;
}
'' eq $op and $self->{$name} = $val;
'clear' eq $op and $self->{$name} = [];
'add' eq $op and push @{$self->{$name}}, $val;
}
close F;
}
sub loadcommandline {
my ($self) = @_;
GetOptions ($self, map {"$_:s"} (grep !/^_/, keys %$self));
}
sub get {
return $_[0]->{$_[1]};
}
sub getrcfile {
return $_[0]->{'_rcfile'};
}
package EditIfc;
use POSIX qw(tmpnam);
sub new {
my ($class) = @_;
# bless me, I'm a hash
my $self = {};
bless $self, $class;
# set up state machine order
my $editstate = 0;
$self->{'estab'} = {
SET0 => $editstate++,
SET1 => $editstate++,
SET2 => $editstate++,
SET3 => $editstate++,
SET4 => $editstate++,
TYPE_WHOLE => $editstate++,
LOCAL_EDIT => $editstate++,
DELETE => $editstate++,
INSERT => $editstate++,
EXIT => $editstate++
};
$self->{'editstate'} = 0;
# return me
return $self;
}
sub useline {
my ($self, $line, $server) = @_;
my $echocmd;
# check for editor prompt
my $editstate = $self->{'editstate'};
my $editprompt = ($line =~ /^\r\*$/);
return unless $editstate || $editprompt;
# dig into the state machine
if ($editstate >= $self->{'estab'}{'SET0'}
&& $editstate <= $self->{'estab'}{'SET4'}
&& $editprompt)
{
my $echocmd = (
$editstate == $self->{'estab'}{'SET0'} && 'set term hcpy' ||
$editstate == $self->{'estab'}{'SET1'} && 'set term noeightbit' ||
$editstate == $self->{'estab'}{'SET2'} && 'set term noedit' ||
$editstate == $self->{'estab'}{'SET3'} && 'set nowrap' ||
$editstate == $self->{'estab'}{'SET4'} && 'set notruncate');
$server->writeln($echocmd);
++$self->{'editstate'};
return $echocmd;
}
if ($editstate == $self->{'estab'}{'TYPE_WHOLE'} && $editprompt) {
$self->{'editbuffer'} = '';
++$self->{'editstate'};
$echocmd = 'type whole';
$server->writeln($echocmd);
return $echocmd;
}
if ($editstate == $self->{'estab'}{'LOCAL_EDIT'}){
if ($line !~ /\[EOB\]\s*$/) {
# Don't trust that the server is getting the
# line breaks right. It doesn't always.
# Consider the difference between the two
# following examples, both of which are
# editing the same text.
#
# }{ 136 3^M
# }{ 137 4^M
# }{ 138 5^M}{
# }{ 139 6^M
# }{ 140 7^M
#
# }{ 136 3^M
# }{ 137 4^M
# }{ 138 5^M
# }{ 139 6^M
# }{ 140 7^M
#
# The old code did
# /^\s*\d+\s{7}(.*?)?$/;
# print TEMP "$1\n";
# but now instead we suck the whole thing into
# a buffer so it should all be right.
$self->{'editbuffer'} .= $line;
}
else {
my $editor = $ENV{'EDITOR'} || 'vi';
# clean up the editbuffer
$self->{'editbuffer'} =~ s/^\s*\d+\s{7}//mg;
$self->{'editbuffer'} =~ s/$//mg;
# write twice so we can diff
my $editorig = tmpnam() . '.qar.txt';
open ORIG, ">$editorig";
print ORIG $self->{'editbuffer'};
close ORIG;
$self->{'edittemp'} = tmpnam() . '.qar.txt';
open TEMP, ">$self->{'edittemp'}";
print TEMP $self->{'editbuffer'};
close TEMP;
# local edit
system $editor, $self->{'edittemp'};
# find where the diffs start
open ORIG, $editorig;
open TEMP, $self->{'edittemp'};
for ($self->{'diffstart'} = 1;
# read from both filehandles before
# testing so that the logic doesn't
# short-circuit the second read
($self->{'origline'} = <ORIG>),
($self->{'templine'} = <TEMP>),
defined $self->{'origline'} && defined $self->{'templine'};
++$self->{'diffstart'})
{
last if $self->{'origline'} ne $self->{'templine'};
}
# don't need ORIG beyond here, but leave
# TEMP open since we'll continue reading
# from it below
close ORIG;
unlink $editorig;
++$self->{'editstate'};
}
return;
}
if ($editstate == $self->{'estab'}{'DELETE'} && $editprompt) {
# only execute the delete command if we didn't
# reach the end of ORIG
if (defined $self->{'origline'}) {
undef $self->{'origline'};
$echocmd = "delete $self->{'diffstart'}:end";
$server->writeln($echocmd);
}
# only execute the insert command if we didn't
# reach the end of TEMP
elsif (defined $self->{'templine'}) {
++$self->{'editstate'};
$echocmd = 'insert end';
$server->writeln($echocmd);
}
# otherwise skip over the INSERT state completely
else {
# advance to EXIT and re-enter the state machine
$self->{'editstate'} = $self->{'estab'}{'EXIT'};
$echocmd = $self->useline($line, $server);
}
return $echocmd;
}
if ($editstate == $self->{'estab'}{'INSERT'}) {
# TEMP is left open from the LOCAL_EDIT state
# above, and the first pertinent line is already
# in $templine. If it's undefined, then we've
# already reached EOF
if (defined $self->{'templine'}) {
chomp $self->{'templine'};
$server->writeln($self->{'templine'});
# get the next line now so it's available the
# next time through the loop
$self->{'templine'} = <TEMP>;
}
else {
++$self->{'editstate'};
$server->write("\032"); # Ctrl-Z
}
return;
}
if ($editstate == $self->{'estab'}{'EXIT'} && $editprompt) {
close TEMP;
unlink $self->{'edittemp'} if $main::config->get('deltemp');
$self->{'editstate'} = 0;
$echocmd = 'ex';
$server->writeln($echocmd);
return $echocmd;
}
}
package main;
use IO::Socket;
sub isbatchcmd {
my ($cmd) = @_;
foreach my $match (@{$main::config->get('batchcmd')}) {
return 1 if $cmd =~ /$match/;
}
return 0;
}
sub doserver {
my ($debug) = @_;
my $listen = IO::Socket::INET->new(
Listen => 5,
LocalAddr => $main::config->get('serveraddr'),
LocalPort => $main::config->get('serverport'),
Reuse => 1,
);
$listen or die "server already running";
my $qs = new QARSession($debug);
my $from = $qs->{from};
$qs->login;
while (1) {
local $SIG{ALRM} = sub { die "alarm\n" };
alarm $main::config->get('servertimeout') * 60;
my $clientref = [$listen->accept];
alarm 0;
$clientref->[0] or last;
$qs->docmd($clientref) or last;
}
}
sub doclient {
my ($sock) = @_;
$| = 1;
# setup communication
my $server = new StreamBuf('server', $sock);
my $plex = new StreamPlex($server);
# pager vars
my $pagerbuf = '';
my $usepager = -1;
my $pagerlines = 0;
my $pagerlaunched = 0;
# user state vars
my $userline = '';
my $userescape = $main::config->get('userescape');
my $editifc = new EditIfc;
# send command to server
my $cmd = $main::config->get('reload') ? 'reload' : join(' ', @ARGV);
my $echocmd = $cmd;
$server->writeln($cmd) if $cmd;
# set up terminal
my $localterm = new LocalTerm;
if (!isbatchcmd($cmd)) {
$plex->addstream(new StreamBuf('user', *STDIN));
$localterm->setpassthru;
}
# set up pageheight
my $pageheight = $main::config->get('pageheight');
$pageheight = $localterm->get('row') || 24 if lc $pageheight eq 'auto';
$usepager = 0 if $pageheight == 0 || !isbatchcmd($cmd);
my $which;
while (($which, $_) = $plex->readln) {
if ($which == $server) {
# server
$_ ||= '';
# handle tilde commands from server
s{~([^~]*)~}{
my ($cmd, $arg) = split /:/, $1;
my $rtn = '';
{
!defined $cmd || $cmd eq '' and $rtn='~' and last;
'cachehit' eq $cmd and do {
print STDERR "Reading from cache...\n";
last;
};
'lines' eq $cmd and do {
$usepager = ($arg > $pageheight) if $usepager < 0;
last;
}
}
$rtn;
}ge;
# skip the echo cmd
if ($echocmd && $_ eq "$echocmd\r\n") {
$echocmd = '';
next;
}
$echocmd = '';
# check for editor prompt
if ($main::config->get('uselocaleditor')) {
$echocmd = $editifc->useline($_, $server) || '';
}
# try to decide if we need a pager
$pagerlines += 1;
$usepager = 1 if $usepager < 0 && $pagerlines > $pageheight;
# spawn a pager if we know we need one
if ($usepager == 1 && ! $pagerlaunched) {
my $pager = $ENV{PAGER} || 'more';
open P, "|$pager" or die "Pager ($pager) launch failed: $!\n";
select P;
$pagerlaunched = 1;
}
# fix control codes
unless ($main::config->get('allowclear')) {
s/\e[DM78]//g; # cursor position
s/\e\[[Hf]/\n/g; # set cursor home
s/\e\[\d+;\d+r//g; # set scroll region
s/\e\[\?6[hl]//g; # turn on/off region
s/\e\[\d+;(\d+)[Hf]/\n\e[$1C/g; # set row and col
s/\e\[\d+[AB]/\n/g; # cursor up/down
s/\e\[\d?J//g; # erase screen
#s/\e\[\d?K/\n/g; # erase line
#s/\e\[.m//g; # reverse video mode
}
# print a line if we've decided about needing a pager
if ($usepager > -1 || !$_) {
# print any buffered lines
if ($pagerbuf) {
print $pagerbuf;
$pagerbuf = '';
}
print;
}
else {
# we haven't yet decided about the pager, so store this line
$pagerbuf .= $_;
}
# quit if server has cut us off
last unless $_;
}
else {
my $disconnect = 0;
$userline .= $_;
$userline =~ s[\Q$userescape\E(.)][
my $mark = $1;
my $rtn = $&;
{
'.' eq $mark and do { $disconnect = 1; $rtn = ''; last};
"\032" eq $mark and do { kill('STOP', $$); $rtn = ''; last};
}
$rtn;
]ge;
$_ = $userline;
$userline = '';
if (substr($_, -1) eq $userescape) {
$userline = $userescape;
$_ = substr($_, 0, length($_) - 1);
}
$server->write($_);
$disconnect and last;
}
}
print "\n";
# wait for pager to close
if ($pagerlaunched) {
close P;
}
}
sub reload {
my ($client) = @_;
print "reloading...";
local $^W = 0;
do $0;
print " done\n";
}
### main program ###
if (defined $main::initted) {
# executad only on reload
$main::config->loadfile;
}
else {
# init globals
$main::initted = 1;
%main::cache = ();
# read and interpret .sqarrc
$main::config = new Config;
$main::config->loadfile;
$main::config->loadcommandline; # only on startup (not on reload)
if (defined $main::config->get('help')) {
my $trans = $INC[0] . "/../../../bin/pod2" . $main::config->get('help');
if (-e $trans) {
system $trans, $0
}
else {
if ($main::config->get('help') !~ /^(usage|)$/i) {
print "\nFailed to find pod translator: $trans";
}
print "\nUsage: $0 [options] [command]
--allowclear boolean allow unfiltered terminal control codes
--batchcmd define which command require no interaction
--clientaddr address connect to server at this address
--clientport port connect to server on this port
--deltemp boolean delete edit session tempfile after use
--help [ usage | text | html ] print this message or reference docs
--listen start a forground server
--mkrc generate a sample .sqarrc file
--pageheight [ lines | auto ] max lines before pager is launched
--password password password to use during server logon
--reload request server to reload .sqarrc
--serveraddr address qar server will listen at this address
--serverport port qar server will listen on this port
--servertimeout minutes max time between client connections
--termtype [ alias | sequence ] term type to report during server logon
--uselocaleditor boolean use local editor instead of VMS editor
--userescape character user prefix for local commands (~)
--username username username to use during server logon\n\n"
}
}
elsif (defined $main::config->get('mkrc')) {
my $rcfile = $main::config->getrcfile;
$rcfile .= ".sample" if -e $rcfile;
open RCFILE, ">$rcfile" or die "Couldn't write rcfile ($rcfile): $!\n";
while (<DATA>) {
last if /__END__/;
print RCFILE;
}
}
elsif (defined $main::config->get('listen')) {
doserver(1);
}
else {
my $serverspawned = 0;
CONNECT: {
my $sock = eval {
# turn off warnings
local $^W = 0;
# try to connect to server
IO::Socket::INET->new(
PeerAddr => $main::config->get('clientaddr'),
PeerPort => $main::config->get('clientport'),
);
};
if (!$sock) {
if ($serverspawned) {
die "Failed to connect local server!\n";
}
else {
warn "Spawning new server...\n";
$serverspawned = 1;
unless (fork) {
doserver(0);
exit;
}
sleep 1;
redo CONNECT;
}
}
doclient($sock);
}
}
exit 0;
}