-
Notifications
You must be signed in to change notification settings - Fork 0
/
msjnc
2345 lines (1947 loc) · 71 KB
/
msjnc
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
#
my $C = 'Copyright 2008-2013 Paul D. Smith <[email protected]>';
#
# MadScientist JNC Session Manager
# I know this script is really long, but it turns out doing anything
# with a GUI takes a lot of--mostly grunt-work--code. Fun!
#
# This is a followup to my previous version, which was written in POSIX sh.
# That version simply invoked the Juniper-provided Network Connect GUI;
# this was problematic because that GUI needed 32bit Java and didn't work
# well with non-Sun/Oracle versions of Java.
#
# This version has its own GUI using Perl/GTK2, so it doesn't need
# any Java at all. Yay!
#
my $L = '
This script is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation; either version 3 of the License, or (at your option)
any later version.
This script is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.';
#
# Requires that Perl GTK2 be installed.
# Typically this means using your package manager to install packages such as
# Red Hat/Fedora: perl-Gtk2 perl-libwww-perl
# Debian/Ubuntu: libgtk2-perl libwww-perl
#
# This script tries to detect the REALM. If there's only one realm possible
# then typically it will be embedded in the web page; in that case we can
# find it. If there is >1 realm then you'll have to look at the page source
# and try to find them. Look for something like:
# <input ... name="realm" value="XXXX">
# and use "XXXX" (no quotes) as the realm value.
my $VERSION = '2.5';
my $RELDATE = '17 Feb 2013';
my $RELURL = 'http://mad-scientist.net/juniper.html';
our $debug = $ENV{__MSJNC_DEBUG__} || 0;
use strict;
use Carp;
use Getopt::Long;
use File::Copy;
use File::Temp qw(tempdir);
use POSIX qw(_exit setsid strftime);
use Net::Ping;
use LWP::Simple;
# Get graphics
use Glib;
use Gtk2;
use Gtk2::SimpleMenu;
use Gtk2::Pango;
# For debug
use Data::Dumper;
$ENV{PATH} = '/sbin:/usr/sbin:/bin:/usr/bin:'.$ENV{PATH};
umask(022);
# General-purpose variables
our $HOME;
my %OPTS;
my $JNPATH;
my $JNCPATH;
my $NCSVC;
my $JNCICON;
my $GETCERT = 'getx509certificate.sh';
my $INTEST = 0;
# Log objects
my $LOGFILE = '.msjnc.log';
my $LOGH = undef;
# GUI objects
my $WIN;
my $TRAY;
my %OBJ;
my $CONN;
my $DESKTOP = '[Desktop Entry]
Name=Network Connect
Comment=MadScientist Juniper Network Connect Session Manager
Type=Application
Terminal=false
StartupNotify=false
Categories=Network;
Actions=Disconnect
Icon=@@ICON@@
Exec=@@CMD@@
[Desktop Action Disconnect]
Name=VPN Session Disconnect
Exec=@@CMD@@ --disconnect';
# --------------- UTILITIES
# Generic small utility functions
# Print version info
sub version {
print "MadScientist JNC Session Manager
Version $VERSION -- $RELDATE
$RELURL\n";
if ($NCSVC && -x $NCSVC) {
local $_ = `$NCSVC -v 2>&1`;
$? == 0 or $_ = "Failed to run $NCSVC.\n".$_;
print "\n$_";
}
exit(0);
}
# Given a timestamp (in time() format) return the elapsed time
# in the form HH:MM:SS
sub elapsed {
my $i = time() - $_[0];
local $_ = '';
if ($i > 86400) {
$_ = int($i/86400).'d ';
$i %= 86400;
}
return sprintf("%s%02d:%02d:%02d", $_, $i/3600, ($i % 3600)/60, $i % 60);
}
# Convert a count of bytes into something more readable
sub cvtbytes {
my $b = shift;
# If we have < 1K use B
$b < 1024 and return "$b B";
# If we have < 1M use K
$b < (1024 * 1024) and return sprintf("%.2f KiB", ($b / 1024.0));
# If we have < 1G use M
$b < (1024 * 1024 * 1024)
and return sprintf("%.2f MiB", $b / (1024.0 * 1024.0));
# Use G
return sprintf("%.2f GiB", $b / (1024.0 * 1024.0 * 1024.0));
}
# Read the contents of a file and return it as a string.
# Remove the trailing newline if there is one.
# Return undef if the file could not be read.
sub readfile {
local $_;
open(my $F, '<', $_[0]) or return undef;
{
local $/ = undef;
$_ = <$F>;
}
close($F) or return undef;
chomp;
return $_;
}
sub logln {
if (! $LOGH) {
open($LOGH, '>>', "$HOME/$LOGFILE") or die "$HOME/$LOGFILE: $!\n";
my $s = select $LOGH; $| = 1;
select $s;
}
local $_ = join('', @_);
s/\n*$//;
print $LOGH strftime("%F %T%z: ", localtime()), "$_\n";
return 1;
}
our $log = \&logln;
# Return a true value if a file has changed since the last time it was called
# or undef if doesn't exist or hasn't changed.
# You need to pass in the previously returned changed value.
sub filechanged {
my ($fn, $info) = @_;
my @s = stat($fn) or return undef;
# If the info is empty, initialize it
$info && %$info or $info = {ino => 0, size => 0, mtime => 0};
# If nothing's changed since the last check, return undef
$info->{ino} == $s[1] && $info->{size} == $s[7] && $info->{mtime} == $s[9]
and return undef;
# Something changed
return {ino => $s[1], size => $s[7], mtime => $s[9]};
}
# This function invokes a child process and writes a password to its stdin
# If the first option is a ref, it's hash of options ($OPT).
# If $OPT->{wait} is not set runs in the background and returns the PID.
# Otherwise, returns 1 if the child succeeds, 0 otherwise.
sub pwd_child {
my $o = ref $_[0] ? shift : {};
my $pwd = shift;
$log->("Writing passwd to child: @_\n");
# We want to write to the child so set up a pipe
my ($rd, $wr);
pipe($rd, $wr) or die "pipe: $!\n";
# Run it!
my $pid = fork();
defined $pid or die "fork: $!\n";
if (! $pid) {
# Child
open(my $N, '>', '/dev/null');
open(STDOUT, '>&', $N);
# Unfortunately sudo -S is broken: if the incoming password is
# bad it still tries to read more. Stupid! Throw out stderr.
open(STDERR, '>&', $N);
# If we're not waiting, change the process group
$o->{wait} or setsid();
# Read stdin from the pipe
open(STDIN, '<&', $rd);
if (!exec(@_)) {
print STDOUT "Failed to run $_[0]: $!\n";
_exit(0);
}
}
# Parent
# Send the password then close
close($rd);
print $wr "$pwd\n";
close($wr);
if (! $o->{wait}) {
$log->("Running pid $pid in the background");
return $pid;
}
# Wait for the child to finish.
$log->("Waiting for pid $pid");
waitpid($pid, 0) == $pid or die "waitpid($pid): $!\n";
my $r = $?;
$log->("result: $r (", ($r >> 8), ")");
return $r == 0;
}
# --------------- CONNECTION PROFILES
# Manage connection profiles
package jnc::Profile;
use Carp;
my $PROFILEFILE = '.msjnc-profiles.cfg';
my $PROF_LOG = undef;
my $PROFILES = {default => 0, list => {}};
my $IDMAX = 0;
my %IDMAP = ();
sub _saveprofiles {
my $sfile = "$main::HOME/$PROFILEFILE";
# Create a dumper object
my $dumper = Data::Dumper->new([ $PROFILES ], [ 'valstore' ])
->Indent(0)->Purity(1)->Deepcopy(1);
my $u = umask(0077);
open(my $S, '>', "$sfile.$$") or die "open: $sfile.$$: $!\n";
print $S $dumper->Dump(), "\n" or die "write: $sfile.$$: $!\n";
close($S) or die "close: $sfile.$$: $!\n";
umask($u);
rename("$sfile.$$", $sfile) or die "rename($sfile.$$, $sfile): $!\n";
return 1;
}
sub _loadprofiles {
my $sfile = "$main::HOME/$PROFILEFILE";
my $new = main::filechanged($sfile, $PROF_LOG) or return 1;
$PROF_LOG = $new;
my $dumped = main::readfile($sfile);
defined $dumped or return 1;
chomp $dumped;
# Eval the contents to set the profile variable.
my $valstore;
my $r = eval($dumped);
$@ and die "Failed to parse $sfile: $@\n";
$PROFILES = $valstore;
$IDMAX = 0;
%IDMAP = ();
while (my ($n, $v) = each %{$PROFILES->{list}}) {
$IDMAP{$v->{pfid}} = $n;
$v->{pfid} > $IDMAX and $IDMAX = $v->{pfid};
}
return 1;
}
sub list {
_loadprofiles();
my @names = sort keys %{$PROFILES->{list}};
return wantarray ? @names : scalar(@names);
}
# Create a new profile. Return a copy.
sub new {
my ($class, $pf) = @_;
$pf or confess "jnc::Profile::get: undefined profile\n";
my $name = $pf->{name}
or confess "jnc::Profile::get: undefined profile name\n";
_loadprofiles();
exists $PROFILES->{list}->{$name}
and confess "jnc::Profile::new: Profile $name already exists\n";
$pf->{pfid} = ++$IDMAX;
$PROFILES->{list}->{$name} = { %$pf };
_saveprofiles();
$IDMAP{$pf->{pfid}} = $name;
return $pf;
}
# Return a copy of the profile data or undef if it doesn't exist
sub get {
my ($class, $name) = @_;
$name or return undef;
_loadprofiles();
exists $PROFILES->{list}->{$name} or return undef;
return { %{$PROFILES->{list}->{$name}} };
}
# Return a copy of the profile data or undef if it doesn't exist
# Look up based on ID, not name
sub get_byid {
my ($class, $id) = @_;
$id or return undef;
_loadprofiles();
exists $IDMAP{$id} or return undef;
return jnc::Profile->get($IDMAP{$id});
}
# Set the profile data
# Returns a copy of the new profile data (a la get())
sub set {
my ($class, $new) = @_;
$new or confess "jnc::Profile::set: undefined new\n";
my $nm = $new->{name} or confess "jnc::Profile::set: undefined name\n";
exists $PROFILES->{list}->{$nm}
or confess "jnc::Profile::set: unknown name\n";
$PROFILES->{list}->{$nm}->{pfid} == $new->{pfid}
or confess "jnc::Profile::set: id doesn't match\n";
$PROFILES->{list}->{$nm} = $new;
_saveprofiles();
return { %$new };
}
# Rename a profile. Return a copy of the new profile, or undef if it fails.
# Do the right thing when renaming the default or active profile.
sub rename {
my ($class, $oldname, $new) = @_;
$oldname or confess "jnc::Profile::rename: undefined oldname\n";
$new or confess "jnc::Profile::rename: undefined new\n";
_loadprofiles();
exists $PROFILES->{list}->{$oldname}
or confess "jnc::Profile::rename: unknown profile $oldname\n";
# Can't overwite an existing profile
exists $PROFILES->{list}->{$new->{name}} and return undef;
$PROFILES->{list}->{$oldname}->{pfid} == $new->{pfid}
or confess "jnc::Profile::rename: id doesn't match\n";
# Rename it
delete $PROFILES->{list}->{$oldname};
$PROFILES->{list}->{$new->{name}} = $new;
_saveprofiles();
return { %$new };
}
# Remove a profile.
# Do the right thing when deleting the default or active profile
sub remove {
my ($class, $name) = @_;
$name or confess "jnc::Profile::remove: undefined name\n";
_loadprofiles();
my $id = $PROFILES->{list}->{$name}->{pfid};
delete $PROFILES->{list}->{$name};
# If this is the default, unset the default
$PROFILES->{default} eq $id and $PROFILES->{default} = 0;
_saveprofiles();
return 1;
}
# Set the default profile. Use '' to unset the default.
# Returns the profile name on success, or undef on error
sub set_default {
my ($class, $name) = @_;
if (! $name) {
$PROFILES->{default} = 0;
} else {
_loadprofiles();
exists $PROFILES->{list}->{$name} or return undef;
$PROFILES->{default} = $PROFILES->{list}->{$name}->{pfid};
}
_saveprofiles();
return $name;
}
# Return the name of the default profile or undef if none
sub get_default {
_loadprofiles();
return $IDMAP{$PROFILES->{default}} || undef;
}
sub debug {
my ($class, $pf) = @_;
foreach my $k (sort keys %$pf) {
print "$k = $pf->{$k}\n";
}
return 1;
}
# --------------- VPN CONTROL
# Manage the current VPN session
package jnc::Session;
use strict;
use Carp;
use Time::Local;
my %CURRENT = ();
my $ACTIVE = 0;
my $LOG = undef;
my $LOG_OFFSET = 0;
my $LOG_LAST = '';
# We have to make a distinction between an ncsvc we started ($CHILD)
# and one we may have just found already running. $PID is the ncsvc pid.
# We guarantee that if $CHILD is set, $PID is always equal to it.
# Conversely, if $PID is not set, $CHILD is always 0.
my $PID = 0;
my $CHILD = 0;
# Convert a date as given in the NC log to time() format
sub _cvtdate {
$_[0] =~ /^(\d\d\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/
or die "INTERNAL: invalid date: $_[0]\n";
return timelocal($6, $5, $4, $3, $2-1, $1-1900);
}
# Get the active profile, or undef if there isn't one.
sub _get_current_pf {
$CURRENT{pfid} or return undef;
my $pf = jnc::Profile->get_byid($CURRENT{pfid});
if (! $pf) {
$log->("Session: Profile $CURRENT{pfid} does not exist.");
$CURRENT{pfid} = 0;
}
return $pf;
}
# Return a copy of the current status of the session
sub get {
return { %CURRENT };
}
sub get_status {
return $CURRENT{status};
}
sub set_active {
my ($class, $id) = @_;
my $pf = jnc::Profile->get_byid($id);
$pf and $ACTIVE = $id;
return $ACTIVE;
}
sub get_active_pf {
return $ACTIVE ? jnc::Profile->get_byid($ACTIVE) : undef;
}
# Given a profile name, if there is a script associated with it
# then run it. Returns false if not invoked or success, or true on failure
sub run_script {
my $pf = _get_current_pf() or return 0;
my $script = $pf->{script} or return 0;
$log->("Session: run user script: $script @_");
if (! -f $script || ! -x $script) {
$log->("Session: $script: $!");
return 1;
}
# Set up the environment
$ENV{jnc_profile} = $pf->{name};
foreach (qw(url host port svcport realm user
proxy proxy_port proxy_domain proxy_user)) {
$ENV{"jnc_$_"} = $pf->{$_} || '';
}
local $_ = `$script @_ 2>&1`;
my $r = $?;
$log->("> $_");
$r == 0 and return 0;
$log->("Session: $script failed: $r (", ($r >> 8), ')');
return 1;
}
# This is invoked when the connection has completed.
sub _connected {
my ($noop, $server, $ctime) = @_;
$log->("DBG: Connected: $server ($ctime)") if $main::debug;
$CURRENT{status} = 'Connected';
$CURRENT{server} = $server;
$CURRENT{ctime} = $ctime;
$CURRENT{timedout} = 0;
$CURRENT{retrying} = 0;
# If we have a "maybe" password, we now know it's good
$CURRENT{pwd_maybe} and $CURRENT{pwd_good} = $CURRENT{pwd_maybe};
$CURRENT{proxy_maybe} and $CURRENT{proxy_good} = $CURRENT{proxy_maybe};
$CURRENT{pwd_maybe} = $CURRENT{proxy_maybe} = undef;
if (! $noop) {
$log->("Session: connected successfully");
run_script('connected');
}
return 1;
}
# Invoke this when a disconnect is discovered
sub _disconnected {
my $noop = $_[0];
$log->("DBG: Disconnected noop=$noop") if $main::debug;
$CURRENT{status} = 'Disconnected';
$CURRENT{address} = '';
$CURRENT{iface} = undef;
$CURRENT{pwd_maybe} = $CURRENT{proxy_maybe} = undef;
if (! $noop) {
$log->("Session: disconnected");
run_script('disconnected');
}
return 1;
}
# Completely clean out the session status
sub clean {
_disconnected(1);
$CURRENT{pfid} = 0;
$CURRENT{pwd_good} = $CURRENT{proxy_good} = undef;
$CURRENT{pwd_maybe} = $CURRENT{proxy_maybe} = undef;
$CURRENT{ctime} = 0;
$CURRENT{received} = $CURRENT{sent} = 0;
$CURRENT{total_ctime} = 0;
$CURRENT{total_received} = $CURRENT{total_sent} = 0;
return 1;
}
# Read the log file and process any change in state.
# Returns 0 if the log didn't exist, 1 otherwise.
sub _readlog {
my $noop = $_[0];
# See if we think the log has been changed since the last time
# If it has, then read it in to detect state changes.
# This is kind of a hack but it's the only mostly-accurate way I know of.
my $new = main::filechanged("$JNCPATH/ncsvc.log", $LOG)
or return 1;
# If the inode is different or the file got smaller it's a new log
! $LOG || $new->{ino} != $LOG->{ino} || $new->{size} < $LOG->{size}
and $LOG_OFFSET = 0;
# Remember the current state, for next time
$LOG = $new;
# Look through the log file, starting where we left off last time
open(my $L, '<', "$JNCPATH/ncsvc.log");
if (! $L) {
$log->("Session: $JNCPATH/ncsvc.log: $!");
return 0;
}
my %prev = %CURRENT;
# Jump to where we last left off. If this fails never mind, we'll
# just read from the beginning.
seek($L, $LOG_OFFSET, 0);
local $_;
# If we have a partial line left over from the last read start with that
$LOG_OFFSET && $LOG_LAST and $_ = $LOG_LAST;
$LOG_LAST = '';
my $l = 0;
# Read in from where we left off
while (1) {
my $n = <$L>;
defined $n or last;
$_ .= $n;
++$l;
# If there is no newline here then save it and stop: partial line
if (! /\n$/) {
$LOG_LAST = $_;
last;
}
if (/^(\d+)\..*\sncsvc\.info\s+Connecting\s+to\b.*?\s([-.a-zA-Z0-9]+)(:[0-9]+)?\s+\(/) {
$log->("DBG: $1: Connecting") if $main::debug;
$CURRENT{status} = 'Connecting';
$CURRENT{server} = $2;
} elsif (/^(\d+)\..*\ssession\.info\s+Connected\s+to\b.*?\s([-.a-zA-Z0-9]+)\s+\(/) {
$log->("DBG: $1: Connected") if $main::debug;
_connected($noop, $2, _cvtdate($1));
} elsif (/(\d+)\..*\ssession\.info\s+disconnecting\s+from\s/) {
$log->("DBG: $1: Disconnecting") if $main::debug;
$CURRENT{status} = 'Disconnecting';
} elsif (/(\d+)\..*\ssession\.info\s+disconnected\s+from\s/) {
$log->("DBG: $1: Disconnected") if $main::debug;
_disconnected($noop);
} elsif (/(\d+)\..*\sncapp\.error\s+Failed\s+to\s+authenticate\s/) {
$log->("DBG: $1: Auth failed") if $main::debug;
clean($noop);
$CURRENT{status} = 'Failed';
} elsif (/^(\d+)\..*\sncphandler\.info\s+session\s+timedout\s+\(/) {
$log->("DBG: $1: Timeout") if $main::debug;
$CURRENT{timedout} = _cvtdate($1);
} elsif (/(\d+)\..*\ssession\.info\s+IVE\s+sent\s+NC\s+IP\s+([.0-9]+)/) {
# Or: /(\d+)\..*\badapter\.info\s+cip\s*=\s*([.0-9]+)\S*\s+mask/
$CURRENT{address} = $2;
}
$_ = '';
}
if ($main::debug) {
$log->("DBG: parsed $l log lines\n") if $main::debug > 1;
$LOG_LAST and $log->("DBG: Partial line: '$LOG_LAST'");
}
$prev{status} eq $CURRENT{status}
or $log->("Session: Change from $prev{status} to $CURRENT{status}");
# Save the amount of file we've already parsed
$LOG_OFFSET = tell($L);
close($L);
return 1;
}
sub _retry {
my $pf = _get_current_pf();
if ($pf && $pf->{retry} && $CURRENT{pwd_good} && ! $CURRENT{retrying}) {
$CURRENT{total_ctime} or $CURRENT{total_ctime} = $CURRENT{ctime};
$CURRENT{total_received} += $CURRENT{received};
$CURRENT{total_sent} += $CURRENT{sent};
$log->("DBG: Retrying") if $main::debug;
jnc::Session->connect() and $CURRENT{retrying} = 1;
} else {
# We can't retry; we're really disconnected.
# Clear out the "total" fields.
$CURRENT{total_ctime} = 0;
$CURRENT{total_received} = $CURRENT{total_sent} = 0;
}
return 1;
}
sub _getpid {
my $arg = $_[0] ? "-p '$_[0]'" : '-e';
# This appears to be the most portable option.
# Kind of gross that we may have to run ps(1) on every update, but...
local $_ = `ps $arg -o pid= -o comm=`;
return m,^\s*(\d+)\s(?:.*/)?ncsvc$, ? $1 : 0;
}
sub update {
# If true, run in no-op mode (don't run scripts, retry, etc.)
my ($class, $noop) = @_;
# Act on any changes to the current status
my $rlog = _readlog($noop);
# If we're connected and don't have a PID, we better be able to find one
if ($CURRENT{status} eq 'Connected' && ! $PID) {
$PID = _getpid();
$PID and $log->("Session: Found previously-running PID $PID\n");
}
if ($CHILD) {
# If we have a child, see if it died and reap it if so
if (waitpid($CHILD, 1) == $CHILD) {
my $r = $?;
$log->("Session: PID $CHILD exited with ", ($r << 8), " ($r)");
$PID = $CHILD = 0;
}
} elsif ($PID && ! _getpid($PID)) {
# We have a non-child PID but it's not valid anymore
$PID = 0;
}
# If we don't have a PID but appear to be connected, disconnect
if (! $PID && $CURRENT{status} ne 'Disconnected') {
$log->("Session: Log says Connected, but no PID: disconnecting.\n");
_disconnected($noop);
}
# If _readlog() failed (no log file?) skip early
if (! $rlog) {
clean();
return get();
}
# If we have an address and we don't know the interface yet, find it
if ($CURRENT{address} && ! $CURRENT{iface}) {
foreach (split /^\d+:\s*/m, `ip addr show`) {
if (m,^(\S+):\s.*\sinet\s\Q$CURRENT{address}\E/,s) {
$CURRENT{iface} = $1;
last;
}
}
}
# If we have an interface get the sent/received bytes values from sysfs
if ($CURRENT{iface}) {
my $d = "/sys/class/net/$CURRENT{iface}/statistics";
$_ = main::readfile("$d/rx_bytes");
if (! defined $_) {
$log->("Session: $d/rx_bytes: $!");
} else {
$CURRENT{received} = $_;
}
$_ = main::readfile("$d/tx_bytes");
if (! defined $_) {
$log->("Session: $d/tx_bytes: $!");
} else {
$CURRENT{sent} = $_;
}
}
if ($CURRENT{status} eq 'Disconnected') {
if ($CURRENT{timedout}) {
# Retry if we're disconnected and we timed out
$log->("Session: Timeout detected at $CURRENT{timedout}");
_retry();
$CURRENT{timedout} = 0;
} else {
# Didn't time out, so reset the counters
$CURRENT{total_ctime} = 0;
$CURRENT{total_received} = $CURRENT{total_sent} = 0;
}
}
return get();
}
# Query the provided host for a certificate and return the pathname.
# Return false if we can't get one.
sub get_cert {
my ($class, $host) = @_;
$log->("Session: Retrieving certificate from $host");
my $cn = "$JNPATH/.cert.$host";
unlink($cn);
my $u = umask(0077);
system("cd '$JNPATH' && /bin/bash ./'$GETCERT' '$host' '$cn' >/dev/null 2>&1");
my $r = $?;
umask($u);
if ($r != 0 || ! -f $cn || -z _) {
$log->("Session: Retrieval failed: $r (", ($r >> 8), ')');
unlink($cn);
return undef;
}
return $cn;
}
# This method is used to connect: creates a session of a profile
sub connect {
my ($class, $pwd, $proxy_pwd) = @_;
# We're starting a new connect; any "maybe" passwords are obsolete
$CURRENT{pwd_maybe} = $CURRENT{proxy_maybe} = undef;
# If the active profile is not the same as the current one, set it
if ($ACTIVE != $CURRENT{pfid}) {
$CURRENT{pfid} = $ACTIVE;
$CURRENT{pwd_good} = $CURRENT{proxy_good} = undef;
$CURRENT{total_ctime} = 0;
$CURRENT{total_received} = $CURRENT{total_sent} = 0;
$CURRENT{timedout} = $CURRENT{retrying} = 0;
}
# If there's no active profile we can't connect.
my $pf = _get_current_pf();
if (! $pf) {
$ACTIVE = 0;
return 0;
}
$log->("Session: connecting using profile $pf->{name}: $pf->{host} user $pf->{user}");
# Remember possible password info, if SecurID is not set
# If we don't have new passwords, try the old ones
if ($pwd) {
$pf->{securid} or $CURRENT{pwd_maybe} = $pwd;
} else {
$pwd = $CURRENT{pwd_good};
}
if ($proxy_pwd) {
$pf->{securid} or $CURRENT{proxy_maybe} = $proxy_pwd;
} else {
$proxy_pwd = $CURRENT{proxy_good};
}
# If we don't have a password, give up
if (! $pwd) {
$log->("Session: no password available");
return 0;
}
my @cmd = ($NCSVC, '-h', $pf->{host}, '-u', $pf->{user},
'-r', $pf->{realm});
$pf->{svcport} and push @cmd, ('-P', $pf->{svcport});
$pf->{url} and push @cmd, ('-U', $pf->{url});
# If we have a proxy add those arguments
if ($pf->{proxy}) {
if (! $proxy_pwd) {
$log->("Session: no proxy password available");
return 0;
}
push @cmd, ('-y', $pf->{proxy}, '-z', $pf->{proxy_port},
'-d', $pf->{proxy_domain}, '-s', $pf->{proxy_user},
'-a', $proxy_pwd);
}
my $cert = jnc::Session->get_cert($pf->{host})
or die "Cannot obtain VPN certificate from $pf->{host}\n";
push @cmd, ('-f', $cert);
$PID = $CHILD = main::pwd_child($pwd, @cmd);
return $CHILD;
}
sub disconnect {
$log->("Session: disconnecting");
system($NCSVC, '-K');
return $? == 0;
}
package main;
# --------------- WINDOW
# Manage the main status window
sub tray_icon_event {
if ($WIN->get_property('visible')) {
$WIN->hide();
} else {
$WIN->show();
}
}
sub window_debug_signal {
my ($widget, $info) = @_;
print "window_debug_signal: $info\n";
return 0;
}
sub window_debug_event {
my ($widget, $event, $info) = @_;
print "window_debug_event: $info\n";
return 0;
}
sub window_state {
my ($w, $e, $d) = @_;
print "Got event $e (", Dumper($e), ")\n";
if ($e->new_window_state('iconified')) {
print "iconified!\n";
} elsif (! $e->new_window_state('iconified')) {
print "not iconified!\n";
}
return 0;
}
# Show a yes/no question. Returns 1 for yes, 0 for no.
sub window_yn {
my $w = shift;
my $d = Gtk2::MessageDialog->new($w, 'destroy-with-parent',
'question', 'yes-no', @_);
$d->show_all();
my $r = $d->run();
$d->destroy();
return $r eq 'yes';
}
# Show an error. Returns 1.
sub window_error {
my $w = shift;
my $d = Gtk2::MessageDialog->new($w, 'destroy-with-parent',
'error', 'ok', @_);
$d->show_all();
my $r = $d->run();
$d->destroy();
return 1;
}
# Show a warning. Returns 1 on ok or 0 on cancel.
sub window_warn {
my $w = shift;
my $d = Gtk2::MessageDialog->new($w, 'destroy-with-parent',
'warning', 'ok-cancel', @_);
$d->show_all();
my $r = $d->run();
$d->destroy();
return $r eq 'ok';
}
# Read a password and return it
sub window_passwd {
my ($title, $msg) = @_;
# create a dialog window
my $dialog = Gtk2::Dialog->new($title, $WIN, 'destroy-with-parent',
'gtk-cancel' => 'cancel',
'gtk-ok' => 'ok');
$dialog->set_default_response('ok');
$dialog->get_content_area()->pack_start(Gtk2::Label->new($msg), 1, 0, 2);
# This is the entry box for the password
my $entry = Gtk2::Entry->new();
$entry->set_visibility(0);
$entry->set_invisible_char('*');
$entry->set_width_chars(25);
$entry->signal_connect(activate => sub { $dialog->response('ok') });
$dialog->get_content_area()->pack_start($entry, 1, 0, 2);
# Run it
$dialog->show_all();
my $r = $dialog->run();
my $pwd = $r eq 'ok' ? $entry->get_text() : undef;
$dialog->destroy();
return $pwd;
}
sub window_delete {
# If you return 0 in the "delete_event" signal handler,
# GTK will emit the "destroy" signal. Returning 1 means
# you don't want the window to be destroyed.
# This is useful for popping up 'are you sure you want to quit?'
# type dialogs.
if (jnc::Session->get_status() =~ /^Connect/) {
window_yn($WIN, "Exiting the application will not disconnect the VPN session.
Do you want to continue to exit?") or return 1;
}
return 0;
}
# Return the name of the active profile
# If there isn't one ask the user to choose
sub window_choose_active {
# Do we have an active session?
my $pf = jnc::Session->get_active_pf();
if (! $pf) {
# Nothing yet
my @l = jnc::Profile->list();
if ($#l > 0) {
# We have >1, so let the user choose
my $pfn = window_choose("Choose active profile:", 'gtk-connect');
$pf = jnc::Profile->get($pfn) or return undef;
} elsif ($#l == 0) {