-
Notifications
You must be signed in to change notification settings - Fork 2
/
autossh.c
1821 lines (1617 loc) · 42.3 KB
/
autossh.c
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
/*
* Start an ssh session (or tunnel) and monitor it.
* If it fails or blocks, restart it.
*
* From the example of rstunnel.
*
* Copyright (c) Carson Harding, 2002-2018.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are freely permitted.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* $Id: autossh.c,v 1.91 2019/01/05 01:23:39 harding Exp $
*
*/
#include "config.h"
#include <sys/types.h>
#include <sys/time.h>
#ifndef HAVE_SOCKLEN_T
typedef int32_t socklen_t;
#endif
#include <sys/socket.h>
#include <sys/utsname.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <limits.h>
#include <sys/wait.h>
#include <setjmp.h>
#include <stdarg.h>
#include <syslog.h>
#include <time.h>
#include <errno.h>
#ifndef HAVE_POLL
# ifdef HAVE_SELECT
# include "fakepoll.h"
# else
# error "System lacks both select() and poll()!"
# endif
#else
# include <poll.h>
#endif
#ifndef __attribute__
# if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 8) || __STRICT_ANSI__
# define __attribute__(x)
# endif
#endif
#ifndef _PATH_DEVNULL
# define _PATH_DEVNULL "/dev/null"
#endif
#ifndef HAVE_DAEMON
# include "daemon.h"
#endif
#ifdef HAVE___PROGNAME
extern char *__progname;
#else
char *__progname;
#endif
const char *rcsid = "$Id: autossh.c,v 1.91 2019/01/05 01:23:39 harding Exp $";
#ifndef SSH_PATH
# define SSH_PATH "/usr/bin/ssh"
#endif
#define POLL_TIME 600 /* 10 minutes default */
#define GATE_TIME 30 /* 30 seconds default */
#define MAX_LIFETIME 0 /* default max lifetime of forever */
#define TIMEO_NET 15000 /* poll on accept() and io (msecs) */
#define MAX_CONN_TRIES 3 /* how many attempts */
#define MAX_START (-1) /* max # of runs; <0 == forever */
#define MAX_MESSAGE 64 /* max length of message we can add */
#define P_CONTINUE 0 /* continue monitoring */
#define P_RESTART 1 /* restart ssh process */
#define P_EXITOK 2 /* exit ok */
#define P_EXITERR 3 /* exit with error */
#define L_FILELOG 0x01 /* log to file */
#define L_SYSLOG 0x02 /* log to syslog */
#define NO_RD_SOCK -2 /* magic flag for echo: no read socket */
#define N_FAST_TRIES 5 /* try this many times fast before slowing */
#define OPTION_STRING "M:V1246ab:c:e:fgi:kl:m:no:p:qstvw:xyACD:E:F:GI:MJKL:NO:PQ:R:S:TW:XY"
int logtype = L_SYSLOG; /* default log to syslog */
int loglevel = LOG_INFO; /* default loglevel */
int syslog_perror; /* use PERROR option? */
FILE *flog; /* log file */
char *writep; /* write port as string */
char readp[16]; /* read port as string */
char *echop; /* echo port as string */
char *mhost = "127.0.0.1"; /* host in port forwards */
char *env_port; /* port spec'd in environment */
char *echo_message = ""; /* message to append to echo string */
char *pid_file_name; /* path to pid file */
int pid_file_created; /* we have created pid file */
time_t pid_start_time; /* time autossh process started */
int poll_time = POLL_TIME; /* default connection poll time */
int first_poll_time = POLL_TIME; /* initial connection poll time */
double gate_time = GATE_TIME; /* time to "make it out of the gate" */
int max_start = MAX_START; /* how many times to run (default no limit) */
double max_lifetime = MAX_LIFETIME; /* how long can the process/daemon live */
int net_timeout = TIMEO_NET; /* timeout on network data */
char *ssh_path = SSH_PATH; /* default path to ssh */
int start_count; /* # of times exec()d ssh */
time_t start_time; /* time we exec()d ssh */
#if defined(__CYGWIN__)
int ntservice; /* set some stuff for running as nt service */
#endif
int newac; /* argc, argv for ssh */
char **newav;
#define START_AV_SZ 16
int cchild; /* current child */
volatile sig_atomic_t exit_signalled; /* signalled outside of monitor loop */
volatile sig_atomic_t restart_ssh; /* signalled to restart ssh child */
volatile sig_atomic_t dolongjmp;
sigjmp_buf jumpbuf;
void usage(int code) __attribute__ ((__noreturn__));
void get_env_args(void);
void add_arg(char *s);
void strip_arg(char *arg, char ch, char *opts);
int ssh_run(int sock, char **argv);
int ssh_watch(int sock);
int ssh_wait(int options);
void ssh_kill(void);
int conn_test(int sock, char *host, char *write_port);
int conn_poll_for_accept(int sock, struct pollfd *pfd);
int conn_send_and_receive(char *rp, char *wp, size_t len,
struct pollfd *pfd, int ntopoll);
#ifndef HAVE_ADDRINFO
void conn_addr(char *host, char *port, struct sockaddr_in *resp);
#else
void conn_addr(char *host, char *port, struct addrinfo **resp);
#endif
int conn_listen(char *host, char *port);
int conn_remote(char *host, char *port);
void grace_time(time_t last_start);
void unlink_pid_file(void);
void errlog(int level, char *fmt, ...)
__attribute__ ((__format__ (__printf__, 2, 3)));
void xerrlog(int level, char *fmt, ...)
__attribute__ ((__format__ (__printf__, 2, 3)));
void doerrlog(int level, char *fmt, va_list ap);
char *timestr(void);
void set_exit_sig_handler(void);
void set_sig_handlers(void);
void unset_sig_handlers(void);
void sig_catch(int sig);
int exceeded_lifetime(void);
unsigned int clear_alarm_timer(void);
void
usage(int code)
{
fprintf(code ? stderr : stdout,
"usage: %s [-V] [-M monitor_port[:echo_port]] [-f] [SSH_OPTIONS]\n",
__progname);
if (code) {
fprintf(stderr, "\n");
fprintf(stderr,
" -M specifies monitor port. May be overridden by"
" environment\n"
" variable AUTOSSH_PORT. 0 turns monitoring"
" loop off.\n"
" Alternatively, a port for an echo service on"
" the remote\n"
" machine may be specified. (Normally port 7.)\n");
fprintf(stderr,
" -f run in background (autossh handles this, and"
" does not\n"
" pass it to ssh.)\n");
fprintf(stderr,
" -V print autossh version and exit.\n");
fprintf(stderr, "\n");
fprintf(stderr, "Environment variables are:\n");
fprintf(stderr,
" AUTOSSH_GATETIME "
"- how long must an ssh session be established\n"
" "
" before we decide it really was established\n"
" "
" (in seconds). Default is %d seconds; use of -f\n"
" "
" flag sets this to 0.\n", GATE_TIME);
fprintf(stderr,
" AUTOSSH_LOGFILE "
"- file to log to (default is to use the syslog\n"
" "
" facility)\n");
fprintf(stderr,
" AUTOSSH_LOGLEVEL "
"- level of log verbosity\n");
fprintf(stderr,
" AUTOSSH_MAXLIFETIME "
"- set the maximum time to live (seconds)\n");
fprintf(stderr,
" AUTOSSH_MAXSTART "
"- max times to restart (default is no limit)\n");
fprintf(stderr,
" AUTOSSH_MESSAGE "
"- message to append to echo string (max 64 bytes)\n");
#if defined(__CYGWIN__)
fprintf(stderr,
" AUTOSSH_NTSERVICE "
"- tweak some things for running under cygrunsrv\n");
#endif
fprintf(stderr,
" AUTOSSH_PATH "
"- path to ssh if not default\n");
fprintf(stderr,
" AUTOSSH_PIDFILE "
"- write pid to this file\n");
fprintf(stderr,
" AUTOSSH_POLL "
"- how often to check the connection (seconds)\n");
fprintf(stderr,
" AUTOSSH_FIRST_POLL "
"- time before first connection check (seconds)\n");
fprintf(stderr,
" AUTOSSH_PORT "
"- port to use for monitor connection\n");
fprintf(stderr,
" AUTOSSH_DEBUG "
"- turn logging to maximum verbosity and log to\n"
" "
" stderr\n");
fprintf(stderr, "\n");
}
exit(code);
}
int
main(int argc, char **argv)
{
int i;
int n;
int ch;
char *s;
int wp, rp, ep = 0;
char wmbuf[256], rmbuf[256];
FILE *pid_file;
int retval = 0;
int sock = -1;
int done_fwds = 0;
int runasdaemon = 0;
int sawargstop = 0;
#if defined(__CYGWIN__)
int sawoptionn = 0;
#endif
#ifndef HAVE___PROGNAME
__progname = "autossh";
#endif
/*
* set up options from environment
*/
get_env_args();
/*
* We accept all ssh args, and quietly pass them on
* to ssh when we call it.
*/
while ((ch = getopt(argc, argv, OPTION_STRING)) != -1) {
switch(ch) {
case 'M':
if (!env_port)
writep = optarg;
break;
case 'V':
fprintf(stdout, "%s %s\n", __progname, VER);
exit(0);
break;
case 'f':
runasdaemon = 1;
break;
#if defined(__CYGWIN__)
case 'N':
sawoptionn = 1;
break;
#endif
case '?':
usage(1);
break;
default:
/* other options get passed to ssh */
break;
}
}
/* if we got it from the environment */
if (env_port)
writep = env_port;
/*
* We must at least have a monitor port and a remote host.
*/
if (!writep || argc == optind)
usage(1);
if (logtype & L_SYSLOG)
openlog(__progname, LOG_PID|syslog_perror, LOG_USER);
/*
* Check for echo port
*/
if ((s = strchr(writep, ':')) != NULL) {
*s = '\0';
echop = s + 1;
ep = strtoul(echop, &s, 0);
if (*echop == '\0' || *s != '\0' || ep == 0)
xerrlog(LOG_ERR, "invalid echo port \"%s\"", echop);
}
/*
* Check, and get the read port (write port + 1);
* then construct port-forwarding arguments for ssh.
*/
wp = strtoul(writep, &s, 0);
if (*writep == '\0' || *s != '\0')
xerrlog(LOG_ERR, "invalid port \"%s\"", writep);
if (wp == 0) {
errlog(LOG_INFO, "port set to 0, monitoring disabled");
writep = NULL;
}
else if (wp > 65534 || wp < 0)
xerrlog(LOG_ERR, "monitor port (%d) out of range", wp);
else {
rp = wp+1;
/* all this for solaris; we could use asprintf() */
(void)snprintf(readp, sizeof(readp), "%d", rp);
/* port-forward arg strings */
n = snprintf(wmbuf, sizeof(wmbuf), "%d:%s:%d", wp, mhost,
echop ? ep : wp);
if (n > sizeof(wmbuf))
xerrlog(LOG_ERR,
"overflow building forwarding string");
if (!echop) {
n = snprintf(rmbuf, sizeof(rmbuf), "%d:%s:%d",
wp, mhost, rp);
if (n > sizeof(rmbuf))
xerrlog(LOG_ERR,
"overflow building forwarding string");
}
}
/*
* Adjust timeouts if necessary: net_timeout is first
* the timeout for accept and then for io, so if the
* poll_time is set less than 2 timeouts, the timeouts need
* to be adjusted to be at least 1/2. Perhaps there should be
* be some padding here as well....
*/
if ((poll_time * 1000) / 2 < net_timeout) {
net_timeout = (poll_time * 1000) / 2;
errlog(LOG_INFO,
"short poll time: adjusting net timeouts to %d",
net_timeout);
}
/*
* Build a new arg list, skipping -f, -M and inserting
* port forwards.
*/
add_arg(ssh_path);
#if defined(__CYGWIN__)
if (ntservice && !sawoptionn)
add_arg("-N");
#endif
for (i = 1; i < argc; i++) {
/*
* We step past the first '--', taking it as ours
* (autossh's). Any further ones we pass to ssh.
*/
if (argv[i][0] == '-' && argv[i][1] == '-') {
if (!sawargstop) {
sawargstop = 1;
continue;
}
}
if (wp && env_port && !done_fwds) {
add_arg("-L");
add_arg(wmbuf);
if (!echop) {
add_arg("-R");
add_arg(rmbuf);
}
done_fwds = 1;
} else if (!sawargstop && argv[i][0] == '-' && argv[i][1] == 'M') {
if (argv[i][2] == '\0')
i++;
if (wp && !done_fwds) {
add_arg("-L");
add_arg(wmbuf);
if (!echop) {
add_arg("-R");
add_arg(rmbuf);
}
done_fwds = 1;
}
continue;
}
/* look for -f in option args and strip out */
strip_arg(argv[i], 'f', OPTION_STRING);
add_arg(argv[i]);
}
if (runasdaemon) {
if (daemon(0, 0) == -1) {
xerrlog(LOG_ERR, "run as daemon failed: %s",
strerror(errno));
}
/*
* If running as daemon, the user likely wants it
* to just run and not fail early (perhaps machines
* are coming up, etc.)
*/
gate_time = 0;
}
/*
* Only if we're doing the network monitor thing.
* Socket once opened stays open for listening for
* the duration of the program.
*/
if (writep) {
if (!echop) {
sock = conn_listen(mhost, readp);
/* set close-on-exec */
(void)fcntl(sock, F_SETFD, FD_CLOEXEC);
} else
sock = NO_RD_SOCK;
}
if (pid_file_name) {
pid_file = fopen(pid_file_name, "w");
if (!pid_file) {
xerrlog(LOG_ERR, "cannot open pid file \"%s\": %s",
pid_file_name, strerror(errno));
}
pid_file_created = 1;
atexit(unlink_pid_file);
if (fprintf(pid_file, "%d\n", (int)getpid()) == 0)
xerrlog(LOG_ERR, "write failed to pid file \"%s\": %s",
pid_file_name, strerror(errno));
fflush(pid_file);
fclose(pid_file);
}
retval = ssh_run(sock, newav);
if (sock >= 0) {
shutdown(sock, SHUT_RDWR);
close(sock);
}
if (logtype & L_SYSLOG)
closelog();
if (retval == P_EXITERR)
exit(1);
exit(0);
}
/*
* Add an argument to the argument array.
*/
void
add_arg(char *s)
{
char *p;
size_t len;
static size_t newamax = START_AV_SZ;
len = strlen(s);
if (len == 0)
return;
if (!newav) {
newav = calloc(START_AV_SZ, sizeof(char *));
if (!newav)
xerrlog(LOG_ERR, "malloc: %s", strerror(errno));
} else if (newac >= newamax-1) {
newamax *= 2;
newav = realloc(newav, newamax * sizeof(char *));
if (!newav)
xerrlog(LOG_ERR, "realloc: %s", strerror(errno));
}
p = malloc(len+1);
if (!p) xerrlog(LOG_ERR, "malloc: %s", strerror(errno));
memmove(p, s, len);
p[len] = '\0';
newav[newac++] = p;
newav[newac] = NULL;
return;
}
/*
* strip an argument option from an option string; strings that
* end up with just a '-' become zero length (add_arg() will
* skip them). An option that enters as '-' is untouched.
*
*/
void
strip_arg(char *arg, char ch, char *opts)
{
char *f, *o;
size_t len;
if (arg[0] == '-' && arg[1] != '\0') {
for (len = strlen(arg), f = arg; *f != '\0'; f++, len--) {
/*
* If f in option string and next char is ':' then
* what follows is a parameter to the flag, and
* what we're stripping may be valid in it. We do
* not validate f in opts: that is really someone
* else's job, and the options may change. In that
* case, this provides a best effort. This is
* terribly inefficient.
*/
if ((o = strchr(opts, *f)) != NULL) {
if (*(o+1) == ':')
return;
}
if (*f == ch)
(void)memmove(f, f+1, len);
}
/* left with "-" alone? then truncate */
if (arg[1] == '\0')
arg[0] = '\0';
}
return;
}
/*
* Ugly, but as we've used so many command args...
*/
void
get_env_args(void)
{
char *s;
char *t;
if ((s = getenv("AUTOSSH_PATH")) != NULL)
ssh_path = s;
if ((s = getenv("AUTOSSH_DEBUG")) != NULL) {
#ifdef HAVE_LOG_PERROR
syslog_perror = LOG_PERROR;
#else
syslog_perror = 0;
logtype |= L_FILELOG;
flog = stderr;
#endif
loglevel = LOG_DEBUG;
} else if ((s = getenv("AUTOSSH_LOGLEVEL")) != NULL) {
loglevel = strtoul(s, &t, 0);
if (*s == '\0' || *t != '\0' ||
loglevel < LOG_EMERG || loglevel > LOG_DEBUG)
xerrlog(LOG_ERR, "invalid log level \"%s\"", s);
}
if ((s = getenv("AUTOSSH_POLL")) != NULL) {
poll_time = strtoul(s, &t, 0);
if (*s == '\0' || poll_time == 0 || *t != '\0' )
xerrlog(LOG_ERR,
"invalid poll time \"%s\"", s);
if (poll_time <= 0)
poll_time = POLL_TIME;
}
if ((s = getenv("AUTOSSH_FIRST_POLL")) != NULL) {
first_poll_time = strtoul(s, &t, 0);
if (*s == '\0' || first_poll_time == 0 || *t != '\0' )
xerrlog(LOG_ERR,
"invalid first poll time \"%s\"", s);
if (first_poll_time <= 0)
first_poll_time = POLL_TIME;
} else {
/*
* If first poll time not explicitly set, first
* poll time should equal poll time.
*/
first_poll_time = poll_time;
}
if ((s = getenv("AUTOSSH_GATETIME")) != NULL) {
gate_time = (double)strtol(s, &t, 0);
if (*s == '\0' || gate_time < 0 || *t != '\0' )
xerrlog(LOG_ERR, "invalid gate time \"%s\"", s);
}
if ((s = getenv("AUTOSSH_MAXSTART")) != NULL) {
max_start = (int)strtol(s, &t, 0);
if (*s == '\0' || max_start < -1 || *t != '\0')
xerrlog(LOG_ERR, "invalid max start number \"%s\"", s);
}
if ((s = getenv("AUTOSSH_MESSAGE")) != NULL) {
if (*s != '\0')
echo_message = s;
if (strlen(echo_message) > MAX_MESSAGE)
xerrlog(LOG_ERR, "echo message may only be %d bytes long",
MAX_MESSAGE);
}
if ((s = getenv("AUTOSSH_PORT")) != NULL)
if (*s != '\0')
env_port = s;
if ((s = getenv("AUTOSSH_MAXLIFETIME")) != NULL) {
max_lifetime = (double)strtoul(s, &t, 0);
if (*s == '\0' || *t != '\0' )
xerrlog(LOG_ERR,
"invalid max lifetime \"%s\"", s);
/* can't really be < 0, as converted as unsigned long */
if (max_lifetime <= 0 )
max_lifetime = MAX_LIFETIME;
else {
if (poll_time > max_lifetime) {
errlog( LOG_INFO,
"poll time is greater than lifetime,"
" dropping poll time to %.0f", max_lifetime );
poll_time = max_lifetime;
}
if (first_poll_time > max_lifetime) {
errlog( LOG_INFO,
"first poll time is greater than lifetime,"
" dropping first poll time to %.0f", max_lifetime );
first_poll_time = max_lifetime;
}
time(&pid_start_time);
}
}
if ((s = getenv("AUTOSSH_PIDFILE")) != NULL)
if (*s != '\0')
pid_file_name = s;
#if defined(__CYGWIN__)
if ((s = getenv("AUTOSSH_NTSERVICE")) != NULL) {
if (*s != '\0' && strncasecmp("yes", s, strlen(s)) == 0) {
ntservice = 1;
logtype = L_FILELOG;
flog = stdout;
}
}
#endif
/*
* Look for this after nt service; in case we may wish to log
* elsewhere than stdout when running under cygrunsrv.
*/
if ((s = getenv("AUTOSSH_LOGFILE")) != NULL) {
flog = fopen(s, "a");
if (!flog)
xerrlog(LOG_ERR, "%s: %s", s, strerror(errno));
logtype = L_FILELOG;
}
return;
}
/*
* Run ssh
*/
int
ssh_run(int sock, char **av)
{
int retval;
struct timeval tv;
/*
* There are much better things. and we all wait
* for solaris to get /dev/random.
*/
gettimeofday(&tv, NULL);
srandom(getpid() ^ tv.tv_usec ^ tv.tv_sec);
set_exit_sig_handler();
while (max_start < 0 || start_count < max_start) {
if (exceeded_lifetime())
return P_EXITOK;
restart_ssh = 0;
start_count++;
grace_time(start_time);
if (exit_signalled) {
errlog(LOG_ERR, "signalled to exit");
return P_EXITERR;
}
time(&start_time);
if (max_start < 0)
errlog(LOG_INFO, "starting ssh (count %d)",
start_count);
else
errlog(LOG_INFO, "starting ssh (count %d of %d)",
start_count, max_start);
cchild = fork();
switch (cchild) {
case 0:
errlog(LOG_DEBUG, "child of %d execing %s",
getppid(), av[0]);
execvp(av[0], av);
errlog(LOG_ERR, "%s: %s", av[0], strerror(errno));
/* else can loop restarting! */
kill(getppid(), SIGTERM);
_exit(1);
break;
case -1:
cchild = 0;
xerrlog(LOG_ERR, "fork: %s", strerror(errno));
break;
default:
errlog(LOG_INFO, "ssh child pid is %d", (int)cchild);
set_sig_handlers();
retval = ssh_watch(sock);
dolongjmp = 0;
clear_alarm_timer();
unset_sig_handlers();
if (retval == P_EXITOK || retval == P_EXITERR)
return retval;
break;
}
}
errlog(LOG_INFO, "max start count reached; exiting");
return P_EXITOK;
}
/*
* Periodically test network connection. On signals, determine what
* happened or what to do with child. Return as necessary for exit
* or restart of child.
*/
int
ssh_watch(int sock)
{
int r;
int val;
static int secs_left;
int my_poll_time = first_poll_time;
time_t now;
double secs_to_shutdown;
#if defined(HAVE_SETPROCTITLE)
setproctitle("parent of %d (%d)",
(int)cchild, start_count);
#endif
for (;;) {
if (restart_ssh) {
errlog(LOG_INFO, "signalled to kill and restart ssh");
ssh_kill();
return P_RESTART;
}
if ((val = sigsetjmp(jumpbuf, 1)) == 0) {
errlog(LOG_DEBUG, "check on child %d", cchild);
/* poll for expired child */
r = ssh_wait(WNOHANG);
if (r != P_CONTINUE) {
errlog(LOG_DEBUG,
"expired child, returning %d", r);
return r;
}
secs_left = clear_alarm_timer();
if (secs_left == 0)
secs_left = my_poll_time;
my_poll_time = poll_time;
if (max_lifetime != 0) {
time(&now);
secs_to_shutdown = max_lifetime - difftime(now,pid_start_time);
if (secs_to_shutdown < poll_time)
secs_left = secs_to_shutdown;
}
errlog(LOG_DEBUG,
"set alarm for %d secs", secs_left);
dolongjmp = 1;
alarm(secs_left);
/* In case we were signalled while setting
all this up */
if (exit_signalled) {
errlog(LOG_INFO, "signalled to exit");
ssh_kill();
return P_EXITERR;
}
pause();
} else {
switch(val) {
case SIGINT:
case SIGTERM:
case SIGQUIT:
case SIGABRT:
errlog(LOG_INFO,
"received signal to exit (%d)", val);
ssh_kill();
return P_EXITERR;
break;
case SIGALRM:
r = exceeded_lifetime();
errlog(LOG_DEBUG,
"received SIGALRM (end-of-life %d)", r);
/* exit if user-configured lifetime exceeded */
if (r) {
ssh_kill();
return P_EXITOK;
}
if (writep && sock != -1 &&
!conn_test(sock, mhost, writep)) {
errlog(LOG_INFO,
"port down, restarting ssh");
ssh_kill();
return P_RESTART;
}
#ifdef TOUCH_PIDFILE
/*
* utimes() with a NULL time argument sets
* file access and modification times to
* the current time
*/
if (pid_file_name &&
utimes(pid_file_name, NULL) != 0) {
errlog(LOG_ERR,
"could not touch pid file: %s",
strerror(errno));
}
#endif
break;
default:
break;
}
}
}
}
/*
* Clear any pending signal timer alarm and return the number of seconds
* before it would have gone off. Return 0 if there was no alarm pending.
*/
unsigned int
clear_alarm_timer(void)
{
unsigned int secs_left = alarm(0);
errlog(LOG_DEBUG,
"clear alarm timer (%d secs left)", secs_left);
return secs_left;
}
/*
* Checks to see if we have exceeded our time to live
* Returns 1 if we have, 0 if we haven't
*/
int
exceeded_lifetime(void)
{
time_t now;
if (max_lifetime > 0 ) {
time(&now);
if (difftime(now, pid_start_time) >= max_lifetime ) {
errlog(LOG_INFO,
"exceeded maximum time to live, shutting down");
return 1;
}
}
return 0;
}
/*
* Wait on child: with options == WNOHANG, poll for
* dead child, else if options == 0, then wait for
* known dead child.
*
* If child was deliberately killed (TERM, INT, KILL),
* the pass message back to restart. If child called exit(0)
* or _exit(0), then pass message on return to give up (P_EXITOK).
* Otherwise death was unnatural (or unintended), and pass
* message back to restart (P_RESTART).
*
* However, if child died with exit(1) on first try, then
* there is some startup error (anything from network
* connection to authentication failure), so we exit.
* If on a restart, however, we keep trying as it must
* have worked once. This doesn't necessarily work if
* the user did an interactive authentication, and then
* isn't there on the restart to enter his password....
* But we can only know very little about what's going
* on inside ssh.
*
* This is further complicated by the behaviour of
* OpenSSH when sent SIGTERM (15). It is possible to
* kill it before it installs the handler for that
* signal, in which case it autossh behaves as above
* and exits. But, in at least interactive use, it
* appears that once the session is established ssh
* installs a handler, and then when signalled (killed)
* it exits with status 255. autossh does not know
* it (ssh) was signalled, so restarts it.
*
*/
int
ssh_wait(int options) {
int status;
int evalue;
time_t now;
if (waitpid(cchild, &status, options) > 0) {
if (WIFSIGNALED(status)) {
switch(WTERMSIG(status)) {
#if 0
/* If someone kills the child, we assume
it was hung up or something and they
wished to restart it. Not entirely sure
want to keep this behaviour or what
signals it should apply to, therefore
the #if 0.
*/
case SIGINT:
case SIGTERM:
case SIGKILL:
/* someone meant it */
errlog(LOG_INFO,
"ssh exited on signal %d; parent exiting",
WTERMSIG(status));
return P_EXITERR;
break;
#endif
default:
/* continue on and restart */
errlog(LOG_INFO,
"ssh exited on signal %d, restarting ssh",
WTERMSIG(status));
return P_RESTART;
break;
}
} else if (WIFEXITED(status)) {
evalue = WEXITSTATUS(status);
if (start_count == 1 && gate_time != 0) {
/*
* If ssh exits too quickly, give up.