File: main.c

package info (click to toggle)
gettyps 2.0.7j-9
  • links: PTS
  • area: non-free
  • in suites: potato, woody
  • size: 364 kB
  • ctags: 285
  • sloc: ansic: 2,644; makefile: 75; sh: 3
file content (1254 lines) | stat: -rw-r--r-- 26,289 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
/*
**	main.c
**
**	main body of program
**
**

	Modified by Jeff Chua (jchua@fedex.com)
	April 25 96
	uugetty sometimes hangs while trying to open() a modem port.
	The last line from /usr/adm/debug will look like ...
		"... D_INIT: opening line /dev/ttyS1"
	Modified so that failure to open the "tty" after 3 attempts will
	terminate the program so that init can restart another uugetty,
	rather than hanging forever!

*/

#define MAIN
#include "main.h"
#include "release.h"
#include <sys/time.h>		/* Jeff Chua, required by setitimer */
#include <grp.h>

#ifdef UUGETTY
#include "uufuncs.h"
#endif /* UUGETTY */

#include "debug.h"

/* forward function declarations
*/

void	timeout();
void	schedalarm();
void	rbalarm();
void	shangup();
void	squit();
void	sterm();
void	ssegv();
int	tputc();
void	exit_usage();
void	initvalues();
void	defs();
void	initline();
void	opentty();
void	dologin();

#ifdef DEBUG
void	debugstart();
#endif /* DEBUG */


/* trivial globals
*/

char	buf[MAXLINE+1];
FILE	*fp;
int	fd;
char	tbuf[64];


#define Perror(s)		{ \
					debug(D_INIT, \
						"Line %d: %s: Error %d: %s\n", \
						__LINE__, s, errno, \
						sys_errlist[errno]); \
					exit(errno); \
				}


#define start_ntimer(n)		sleep_msec(n)
#define start_timer()		sleep_msec(10000)	/* 10 seconds */
#define cancel_timer()		sleep_msec(0)

void sleep_msec(long msec);
void action(int signum);

void sleep_msec(long msec)
{
	struct itimerval rttimer;
	struct itimerval old_rttimer;
	long sec, usec;
	struct sigaction act;

        act.sa_handler = action;
        sigemptyset(&act.sa_mask);
        act.sa_flags = SA_NOMASK;	/* allow own signal to be received */
        if(sigaction(SIGALRM, &act, NULL))		/* called by pause() */
		Perror("sigaction");

	sec = msec / 1000;
	usec = (msec % 1000) * 1000;

	/* set timer to wait once for "msec" seconds */
	/* note that interval must be 0 to wait once only ... */
	/* setting interval to non-zero will repeat forever until cancelled */
	rttimer.it_value.tv_sec		= sec;	/* initial wait, second */
	rttimer.it_value.tv_usec	= usec; /* initial wait, microsecond */
	rttimer.it_interval.tv_sec	= sec;	/* wait interval, second */
	rttimer.it_interval.tv_usec	= usec;	/* wait interval, microsecond */

	if(setitimer(ITIMER_REAL, &rttimer, &old_rttimer))
		Perror("setitimer");
}

void action(int signum)
{
	/*
	static count = 0;
	*/

	switch(signum) {
		case SIGALRM:
				/* called by setitimer */
				/*
				debug(D_INIT, "%s (%d)", "timeout!", count++);
				*/
				break;
		default:
				debug(D_INIT, "unknown signal %d", signum);
				break;
	}
}



/*
** main
*/

int main(argc, argv)
int 	argc;
char 	**argv;
{
	initvalues();		/* initialize all runtime variables */
	defs(argc, argv);	/* parse command line and defaults file */

#ifdef UUGETTY
	waitlocks();		/* hold on 'til the lockfiles are gone */
#endif /* UUGETTY */

	start_timer();
	initline();		/* initialize the line */
	cancel_timer();

	opentty();		/* open & initialize the tty */
	dologin();		/* get username and start login */

	return 0;
}


/* 
** initvalues
**
** initialize all runtime stuff to default values
*/

void initvalues()
{
	(void) signal(SIGINT,  SIG_IGN);	/* ignore ^C */
	(void) signal(SIGQUIT, squit);
	(void) signal(SIGTERM, sterm);
	(void) signal(SIGSEGV, ssegv);
	(void) signal(SIGHUP, shangup);

	strcpy(term, 	"unknown");		/* tty type */
	Device =	"unknown";		/* tty device */
	InitDevice =	Device;			/* device to init */
	LineD =		(char *) NULL;		/* lined */
	AutoBaud = 	FALSE;			/* no autobauding */
	AutoRate[0] = 	'\0';
	Check = 	FALSE;			/* ! check files and exit */
	CheckFile =	(char *) NULL;
	GtabId =	(char *) NULL;
	NoHangUp =	FALSE;			/* hangup the line first */
	TimeOut =	0;			/* no timeout */
	Version =	"/proc/version";	/* version for @V subst */
	delay = 	0;			/* delay before prompt */
	speed =		(char *) NULL;		
	gclear =	TRUE;			/* clear the screen */
	glogin =	LOGIN;			/* login program */
	waitchar =	FALSE;			/* don't wait for a char */
	waitfor =	(char *) NULL;		/* no waitfor string */
	Connect =	(char *) NULL;		/* no connect string */
	defname =	(char *) NULL;		/* no defaults file */

#ifdef ISSUE
	issue =		ISSUE;			/* login banner */
#endif /* ISSUE */

#ifdef FIDO
	fido =		(char *) NULL;		/* fido program */
	emsi =		(char *) NULL;		/* emsi yes or no */
#endif /* FIDO */

#ifdef SCHED
	allow =		TRUE;			/* no scheduling */
#endif /* SCHED */

#ifdef DEBUG
	Debug =		0;			/* no debugging */
	Dfp =		NULL;			/* no debugging file */
#endif /* DEBUG */

#ifdef WARNCASE
	WarnCase =	TRUE;			/* moan about all caps */
#endif /* WARNCASE */

#ifdef RBGETTY
	minrbtime = 	8;			/* min time to call back */
	maxrbtime =	60;			/* max time to call back */
	interring =	6;			/* time between rings */
	minrings = 	1;			/* min rings to set off rb */
	maxrings =	3;			/* max rings to set off rb */
	rbmode = 	FALSE;			/* off by default */
#endif /* RBGETTY */

#ifdef UUGETTY
	MyName =	"uugetty";		/* hello... my name is */
#else
	MyName =	"getty";
#endif /* UUGETTY */
}


#ifdef SCHED
/*
** SetSched
**
** parse the SCHED information
*/

#define TS2SEC(a)	((a).tm_sec + (60 * (a).tm_min) + \
			(3600 * (a).tm_hour) + (86400 * (a).tm_wday))
#define CMP_TIME(a,b)	(TS2SEC(a) - TS2SEC(b))

void setsched(p)
char	*p;
{
	time_t		t_cur;
	struct tm	*cur, tb, te;
	int		count;
	char 		*s;

/* set up the time base
*/
	(void) time(&t_cur);
	cur = localtime(&t_cur);
	debug(D_SCH, "current time: %d:%d:%d", cur->tm_wday, cur->tm_hour,
		cur->tm_min);

/* parse the sched line
*/
	count = 0;
	allow = FALSE;
	tb.tm_sec = te.tm_sec = 0;
	while(sscanf((s = nextword(p, &count)), "%d:%d:%d-%d:%d:%d",
		     &tb.tm_wday, &tb.tm_hour, &tb.tm_min, 
		     &te.tm_wday, &te.tm_hour, &te.tm_min) == 6) {
		p += count;
		debug(D_SCH, "processing field %s", s);

/* hadle week overlaps
*/

		if(CMP_TIME(te, tb) < 0) {
			if(CMP_TIME(*cur, te) < 0)
				tb.tm_wday -= 7;
			else
				te.tm_wday += 7;
			debug(D_SCH, 
			 "week overlap detected.  New range: %d:%d:%d-%d:%d:%d",
			 tb.tm_wday, tb.tm_hour, tb.tm_min,
			 te.tm_wday, te.tm_hour, te.tm_min);
		}

/* set alarm based on times
*/
		if((CMP_TIME(tb, *cur) > 0) && 
		  ((TS2SEC(tb) < alrm) || (alrm == 0))) alrm = TS2SEC(tb);
		if((CMP_TIME(te, *cur) > 0) && 
		  ((TS2SEC(te) < alrm) || (alrm == 0))) alrm = TS2SEC(te);

/* set allow based on this
*/
		if ((CMP_TIME(tb, *cur) < 0) && 
		    (CMP_TIME(*cur, te) < 0)) allow = TRUE;
	}
	alrm -= TS2SEC(*cur);

	debug(D_SCH, "Alarm set to: %u", alrm);
	debug(D_SCH, "Allow: %s", ((allow) ? "TRUE" : "FALSE"));
}
#endif /* SCHED */


/*
** defs
**
** parse the command line and the defaults file
*/

void defs(count, args)
int	count;
char	**args;
{
	register int	c;
	DEF		**def;
	char		*p;
	char		termcap[1024];

/* first, the command line
*/

	while((c = getopt(count, args, "RC:D:ac:d:hr:t:w:")) != EOF) {
		switch(c) {
#ifdef RBGETTY
			case 'R':
				rbmode = TRUE;
				break;
#endif /* RBGETTY */
			case 'C':
				Connect = optarg;
				break;
			case 'D':
#ifdef DEBUG
				(void) sscanf(optarg, "%o", &Debug);
				if(Debug && Dfp == 0) debugstart();
#else
				logerr("DEBUG not compiled in");
#endif /* DEBUG */
				break;
			case 'a':
				InitDevice = optarg;
				break;
			case 'c':
				Check = TRUE;
				CheckFile = optarg;
				break;
			case 'd':
				defname = optarg;
				break;
			case 'h':
				NoHangUp = TRUE;
				break;
			case 'r':
				waitchar = TRUE;
				delay = (unsigned) atoi(optarg);
				break;
			case 't':
				TimeOut = (unsigned) atoi(optarg);
				break;
			case 'w':
				waitchar = TRUE;
				waitfor = optarg;
				break;
			case '?':
				exit_usage(2);
		}
	}

	
/* if we're just checking, exit here
*/

	if(Check) {
		(void) signal(SIGINT, SIG_DFL);
		(void) gtabvalue((char *) NULL, G_CHECK);
		exit(0);
	}


/* get line, speed, tty type, lined
*/

	if(optind < count)
		Device = args[optind++];
	else {
		logerr("no line given");
		exit_usage(2);
	}
	if(optind < count) GtabId = args[optind++]; 
	if(optind < count) strncpy(term, args[optind++], sizeof(term));
	if(optind < count) LineD = args[optind++];


/* check /etc/ttytype if term was not set on the command line
*/

#ifdef TTYTYPE
	if (strequal(term, "unknown")) {
		if(!(fp = fopen(TTYTYPE, "r"))) {
			logerr("open on %s failed: %s", TTYTYPE, 
				strerror(errno));
		} else {
			while((fscanf(fp, "%s %s", name, line)) != EOF) {
				if (strequal(line, Device)) {
					(void) strncpy(term, name, 
						sizeof(term));
					break;
				}
			}
			(void) fclose(fp);
		}
	}
#endif
      
	
/* now, get all that info in the defaults file
*/

	def = defbuild(defname);
#ifdef DEBUG
	if((p = defvalue(def, "DEBUG"))) (void) sscanf(p, "%o", &Debug);
	if(Debug) debugstart();
#endif /* DEBUG */
	if(! (SysName = defvalue(def, "SYSTEM"))) SysName = getuname();
	if((Version = defvalue(def, "VERSION")) && (*Version == '/')) {
		if((fp = fopen(Version, "r"))) {
			(void) fgets(buf, sizeof(buf), fp);
			(void) fclose(fp);
			buf[strlen(buf)-1] = '\0';
			Version = strdup(buf);
		}
	}
	if((p = defvalue(def, "LOGIN"))) glogin = p;
	if((p = defvalue(def, "ISSUE"))) issue = p;
	if((p = defvalue(def, "CLEAR")) && (strequal(p, "NO"))) 
		gclear = FALSE;
	if((p = defvalue(def, "HANGUP")) && (strequal(p, "NO"))) 
		NoHangUp = TRUE;
	if((p = defvalue(def, "WAITCHAR")) && (strequal(p, "YES")))
		waitchar = TRUE;
	if((p = defvalue(def, "DELAY"))) delay = (unsigned) atoi(p);
	if((p = defvalue(def, "TIMEOUT"))) TimeOut = atoi(p);
	if((p = defvalue(def, "CONNECT"))) Connect = p;
	if((p = defvalue(def, "WAITFOR"))) {
		waitchar = TRUE;
		waitfor = p;
	}
	if((p = defvalue(def, "INIT"))) init = p;  
	if((p = defvalue(def, "INITLINE"))) InitDevice = p;
#ifdef FIDO
	fido = defvalue(def, "FIDO");
	emsi = defvalue(def, "EMSI");
#endif /* FIDO */

#ifdef SCHED
	if((p = defvalue(def, "SCHED"))) {
		setsched(p);

		if((! allow)) init = defvalue(def, "OFF");
	}
#endif /* SCHED */

#ifdef RBGETTY
	if((p = defvalue(def, "MINRBTIME"))) minrbtime = atoi(p);
	if((p = defvalue(def, "MAXRBTIME"))) maxrbtime = atoi(p);
	if((p = defvalue(def, "INTERRING"))) interring = atoi(p);
	if((p = defvalue(def, "MINRINGS"))) minrings = atoi(p);
	if((p = defvalue(def, "MAXRINGS"))) maxrings = atoi(p);
	if((p = defvalue(def, "RINGBACK")) && (strequal(p, "YES"))) rbmode = TRUE;
#endif /* RBGETTY */

/* find out how on earth to clear the screen
*/
	clrscr="";     /* initialize clrscr in case term=unknown or not specified in inittab */
	if(! strequal(term, "unknown")) {
		p = tbuf;
		if((tgetent(termcap, term) == 1)
		  && (! (clrscr = tgetstr("cl", &p)))) clrscr = "";
	}

/* construct /dev/ names for the lines
*/
	(void) sprintf(devname, "/dev/%s", Device);
	if(strequal(InitDevice, "unknown")) InitDevice = Device;
	(void) sprintf(initdevname, "/dev/%s", InitDevice);

#ifdef UUGETTY
	(void) sprintf(buf, LOCK, Device);
	lock = strdup(buf);
	if((p = defvalue(def, "ALTLOCK"))) {
		(void) sprintf(buf, LOCK, p);
		altlock = strdup(buf);
	} else if(! strequal(Device, InitDevice)) {
		(void) sprintf(buf, LOCK, InitDevice);
		altlock = strdup(buf);
	}

	debug(D_LOCK, "lock = (%s), altlock = (%s)", lock, altlock);
#endif /* UUGETTY */
}


#ifdef DEBUG
/*
** debugstart
**
** open up the debug file
*/

void debugstart()
{
	time_t	clock;

#if !defined(SYSLOG) || !defined(SYSL_DEBUG)
	(void) sprintf(buf, "/tmp/%s:%s", MyName, Device);
	if(! (Dfp = fopen(buf, "a+"))) {
		logerr("open debug file \"/tmp/%s:%s\" failed: %s",
		       MyName, Device, strerror(errno));
		exit(FAIL);
	} 
	if (fileno(Dfp) < 3) {
		if((fd = fcntl(fileno(Dfp), F_DUPFD, 3)) > 2) {
			(void) fclose(Dfp);
			Dfp = fdopen(fd, "a+");
		}
	}
	debug(D_ALL, "----------");
#endif
	(void) time(&clock);
	debug(D_ALL, "%s version %s started at %s", MyName, 
	      RELEASE, ctime(&clock));
}
#endif /* DEBUG */



#ifdef LOGUTMP
/*
** doutmp
**
** update the utmp and wtmp files
*/

void doutmp()
{
	int 		pid;
	struct utmp	*utp;
	struct utmp	uts;
	struct flock	fl;

	debug(D_UTMP, "update utmp/wtmp files");

	pid = getpid();

	setutent();
	while((utp = getutent()) && !(utp->ut_type == INIT_PROCESS &&
		utp->ut_pid == pid));

	if (utp)
		memcpy(&uts, utp, sizeof(uts));
	/*
	Leave ut_id alone, it should contain the 2-character key at the
	front of each inittab line, not an abbreviation for the tty line,
	because ttyS20 and ttyS2 both get the same id.
	And the pututline function locates the utmp entry to be updated by
	comparing ut_id's with the one passed in.
	Alan Wendt 7/26/95
	*/
	else {
		memset(&uts, 0, sizeof(uts));
		strncpy(uts.ut_id, Device+3, sizeof(uts.ut_id));
	}

	strncpy(uts.ut_line, Device, sizeof(uts.ut_line));
	uts.ut_pid = pid;
	uts.ut_type = LOGIN_PROCESS;
	time(&uts.ut_time);
	
	debug(D_UTMP, "adding utmp entry: type: %d, pid: %d, line: %s, id: %c%c, time: %d, user: %s, host: %s, addr: %d",
		uts.ut_type, uts.ut_pid, uts.ut_line,
		(uts.ut_id[0] ? uts.ut_id[0] : ' '), 
		(uts.ut_id[1] ? uts.ut_id[1] : ' '), 
		uts.ut_time, uts.ut_user, uts.ut_host, uts.ut_addr);
	
	pututline(&uts);
	endutent();

#if __GLIBC__ > 1
	updwtmp(WTMP_FILE, &uts);
	debug(D_UTMP, "adding wtmp entry");
#else
	if((fp = fopen(WTMP_FILE, "a"))) {
		debug(D_UTMP, "locking %s", WTMP_FILE);
		fl.l_type = F_WRLCK;
		fl.l_whence = fl.l_len = fl.l_start = 0;
		if (fcntl (fileno (fp), F_SETLKW, &fl) >= 0) {
		  (void) fseek(fp, 0L, 2);
		  debug(D_UTMP, "adding wtmp entry");
		  (void) fwrite((char *)&uts, sizeof(struct utmp), 
				1, fp);
		} else
		  logerr("flock of %s failed: %s", WTMP_FILE, strerror(errno));
		(void) fclose(fp);
	}
#endif /* __GLIBC__ > 1 */
}
#endif /* LOGUTMP */


/*
** initline
**
** initialize the line, do waitchar, waitfor
*/

void initline()
{
	TERMIO		termio;
	char		ch;
	int		flags;
	char *		wait = waitfor;

	int		busys = 0;

/* set the line owned by root
*/

#ifdef DEBIAN
	{
		/* tty to root.dialout 660 */
		struct group *gr;
		int id;
		id = (gr = getgrnam("dialout")) ? gr->gr_gid : 0;
		chown(devname, 0, id);
		chmod(devname, 0660);

		/* vcs,vcsa to root.sys 600 */
		if (!strncmp(devname, "tty", 3) && isdigit(devname[3])) {
			char *vcs, *vcsa;

			vcs = malloc(strlen(devname));
			vcsa = malloc(strlen(devname) + 1);
			id = (gr = getgrnam("sys")) ? gr->gr_gid : 0;

			if (vcs) {
				strcpy(vcs, "vcs");
				strcpy(vcs+3, devname+3);
				chown(vcs, 0, id);
				chmod(vcs, 0600);
				free(vcs);
			} else logerr("malloc() failed in initline()\n");

			if (vcsa) {
				strcpy(vcsa, "vcsa");
				strcpy(vcsa+4, devname+3);
				chown(vcsa, 0, id);
				chmod(vcs, 0600);
				free(vcsa);
			} else logerr("malloc() failed in initline()\n");
		}
	}
#else
	(void) chmod(devname, 0600);
	(void) chown(devname, 0, 0);
#endif /* DEBIAN */


/* update utmp/wtmp
*/

#ifdef LOGUTMP
	doutmp();
#endif /* LOGUTMP */


/* close any old stdin, stdout, stderr
*/

	(void) close(0);
	(void) close(1);
	(void) close(2);


/* vhangup the line
*/
	debug(D_INIT, "opening line %s", devname);

	while(((fd = open(devname, O_RDWR | O_NDELAY)) < 0)) {
		switch(errno) {
			case EBUSY:
				if(++busys > 3)	/* try for 3 times */
					exit(FAIL);
				debug(D_INIT, "%s busy %d", devname, busys);
				pause();
				break;
			case EAGAIN:
				logerr("open failed on \"%s\": %s", devname, 
				strerror(errno));
				exit(FAIL);
			default:
				Perror("open");
		}
	}

	ioctl(fd, TIOCSCTTY, 1);
	(void) ioctl(fd, TCGETS, &termio);
	if(NoHangUp) {
		termio.c_cflag &= ~HUPCL;
	} else {
		termio.c_cflag &= ~CBAUD;
		termio.c_cflag |= B0;
	}
	(void) ioctl(fd, TCSETSF, &termio);
	if(! NoHangUp) sleep(2);
	gtab = gtabvalue(GtabId, G_FORCE);
	settermio(&(gtab->itermio), INITIAL);
#ifndef GDB_FRIENDLY
	(void) signal(SIGHUP, SIG_IGN);
	vhangup();
	(void) signal(SIGHUP, shangup);
#endif
	close(fd);


/* now, the init device is opened ONLY if INIT or WAITCHAR is requested
*/

	if((init) || (waitchar)) {
		debug(D_INIT, "opening init line: %s", initdevname);
		if((fd = open(initdevname, O_RDWR | O_NDELAY)) < 0)
			if((errno == EBUSY) || (errno == EAGAIN)) {
				debug(D_INIT, 
				  "line in use... exiting to reinit");
				exit(0);
			} else {
				logerr("open failed on \"%s\": %s",
				       initdevname, strerror(errno));
				exit(FAIL);
			}
		if(fd != 0) {
			logerr("open fd != 0, please report this bug [1]");
			exit(FAIL);
		}
		if(dup(0) != 1) {
			logerr("dup fd != 1, please report this bug [1]");
			exit(FAIL);
		}
		if(dup(0) != 2) {
			logerr("dup fd != 2, please report this bug [1]");
			exit(FAIL);
		}

		setbuf(stdin, (char *) NULL);
		setbuf(stdout, (char *) NULL);
		setbuf(stderr, (char *) NULL);

		settermio(&(gtab->itermio), INITIAL);

		flags = fcntl(STDIN, F_GETFL, 0);
		(void) fcntl(STDIN, F_SETFL, flags & ~O_NDELAY);

/* init the line
*/

		if(init) {
			debug(D_INIT, "initializing line");

/* set CLOCAL and other stuff for init, so ATZ works right
*/
			(void) ioctl(STDIN, TCGETS, &termio);
			termio.c_cflag |= CLOCAL;
			termio.c_iflag &= ~(ICRNL);
			termio.c_lflag &= ~(ICANON);
			(void) ioctl(STDIN, TCSETSF, &termio);

			if(chat(init) == FAIL) {
				debug(D_INIT, "init failed... aborting");
				logerr("warning: INIT sequence failed on %s",
				       initdevname);
				exit(FAIL);
			}

			settermio(&(gtab->itermio), INITIAL);
		}
	}

/* set the alarm if requested
*/

#ifdef SCHED
	if(alrm) {
		(void) signal(SIGALRM, schedalarm);
		(void) alarm(alrm);
		debug(D_SCH, "SCHED alarm set");
	}
#endif /* SCHED */

/* wait for a char
*/
#ifdef SCHED
	if(allow)
#endif /* SCHED */
	  if(waitchar) {
		debug(D_INIT, "waiting for a character...");

		(void) ioctl(STDIN, TCFLSH, 0);
		(void) read(STDIN, &ch, 1);		/* blocks */
		debug(D_INIT, "got it");

#ifdef UUGETTY
/* check the lockfiles
*/
		if (checklock(lock) || (altlock && checklock(altlock))) {
			(void) signal(SIGHUP, SIG_IGN);
			ioctl(STDIN, TIOCNOTTY);
			exit(0);
		}
#endif /* UUGETTY */

		if(wait) {
			if(ch == *wait) wait++;
			if((*wait) && (expect(wait) == FAIL)) {
				debug(D_INIT, "WAITFOR match failed");
				exit(0);
			}
		}
	}
}


#ifdef RBGETTY
/*
** dorb
**
** watch the pattern of incoming rings (defined by the WAITFOR
** string) to do a ringback connect
**
** contributed by: Shane Alderton (shanea@extra.ucc.su.oz.au)
*/

void dorb()
{
	time_t	lasttime = 0;
	time_t	currenttime = 0;
	time_t	elapsed;
	int	ringcount = 1;
	boolean success = FALSE;
	char *	wait;
	char	ch;

	while(! success) {
		(void) time(&lasttime);
		(void) signal(SIGALRM, rbalarm);
		(void) alarm(maxrbtime);

		debug(D_RB, "waiting for another ring...");
		(void) ioctl(STDIN, TCFLSH, 0);
		(void) read(STDIN, &ch, 1);		/* this blocks */
		debug(D_RB, "got something");

		(void) alarm(0);
		(void) signal(SIGALRM, SIG_DFL);
		wait = waitfor;
		if(wait) {
			if(ch == *wait) wait++;
			if((*wait) && (expect(wait) == FAIL)) {
				debug(D_RB, "WAITFOR match failed");
				exit(0);
			}
			debug(D_RB, "WAITFOR string matched");
		}
		
		(void) time(&currenttime);
		elapsed = currenttime - lasttime;

		if(elapsed <= interring) {
			ringcount++;
			debug(D_RB, "got ring number %d.", ringcount);
		} else if (elapsed < minrbtime) {
			debug(D_RB, "%d rings then one too quickly... ",
				ringcount);
			debug(D_RB, "treating as a new call");
			ringcount = 1;
		} else if (ringcount > maxrings) {
			debug(D_RB, "%d rings... too many", ringcount);
			debug(D_RB, "... exiting to reinit");
			exit(0);
		} else if (ringcount < minrings) {
			debug(D_RB, "%d rings... too few", ringcount);
			debug(D_RB, "... exiting to reinit");
			exit(0);
		} else { 
			debug(D_RB, "got ringback...");
			success = TRUE;
		}
	}
	debug(D_RB, "ringback finished");
}
#endif /* RBGETTY */
		


/*
** opentty
**
** open the tty device.
** the tty is opened in blocking mode, unless WAITFOR is specified
*/

void opentty()
{
	int	flags, i, cbaud, nspeed;
	char	ch;
	GTAB	*gt;

/* close any old stdin, stdout, stderr
*/
	(void) close(0);
	(void) close(1);
	(void) close(2);

#ifdef SCHED
/* handle allow
*/

	debug(D_SCH, (allow ? "not sleeping" : "sleeping"));
	while(! allow) pause();
#endif /* SCHED */

	debug(D_RUN, "opening line: %s", devname);

	if((fd = open(devname, (waitfor) ? 
	  (O_RDWR | O_NDELAY) : (O_RDWR))) < 0) {
		if (errno == EAGAIN) {
			debug(D_RUN, 
			  "open got EAGAIN... exiting to reinitialize");
			exit(0);
		}
		logerr("open failed on \"%s\": %s", devname, strerror(errno));
		exit(FAIL);
	}
	if(fd != 0) {
		logerr("open fd != 0, please report this bug [2]");
		exit(FAIL);
	}
	if(dup(0) != 1) {
		logerr("dup fd != 1, please report this bug [2]");
		exit(FAIL);
	}
	if(dup(0) != 2) {
		logerr("dup fd != 2, please report this bug [2]");
		exit(FAIL);
	}

#ifdef UUGETTY
/* now we can lock the line
*/
	lockline();
#endif /* UUGETTY */

	ioctl(fd, TIOCSCTTY, 1);
#ifndef GDB_FRIENDLY
	setpgrp();
#endif

	setbuf(stdin, (char *) NULL);
	setbuf(stdout, (char *) NULL);
	setbuf(stderr, (char *) NULL);

	flags = fcntl(STDIN, F_GETFL, 0);
	(void) fcntl(STDIN, F_SETFL, flags & ~O_NDELAY);

	gtab = gtabvalue(GtabId, G_FORCE);
	settermio(&(gtab->itermio), INITIAL);

	if(delay) {
		debug(D_RUN, "delay(%d)", delay);

		(void) sleep(delay);
		(void) fcntl(STDIN, F_SETFL, flags | O_NDELAY);
		while (read(STDIN, &ch, 1) == 1);
		(void) fcntl(STDIN, F_SETFL, flags & ~O_NDELAY);
	}

#ifdef RBGETTY
	if(rbmode) dorb();
#endif /* RBGETTY */

	if(Connect) {
		debug(D_RUN, "performing connect sequence");

		cbaud = 0;
		if(strequal(Connect, "DEFAULT")) Connect = DEF_CONNECT;
		if((chat(Connect)) == FAIL) {
			logerr("warning: CONNECT sequence failed");
			debug(D_RUN, "connect sequence failed... aborting");
			exit(FAIL);
		}
		if(AutoBaud) {
			debug(D_RUN, "AutoRate = (%s)", AutoRate);
#ifdef TELEBIT
			if(strequal(AutoRate, "FAST")) 
				(void) strcpy(AutoRate, TB_FAST);
#endif /* TELEBIT */
			if((nspeed = atoi(AutoRate)) > 0)
				for (i=0; speedtab[i].nspeed; i++)
					if(nspeed == speedtab[i].nspeed) {
						cbaud = speedtab[i].cbaud;
						speed = speedtab[i].speed;
						break;
					}
		}
		if(cbaud) {
			debug(D_RUN, "setting speed to %s", speed);
			if((gt = gtabvalue(speed, G_FIND)) && 
			  strequal(gt->cur_id, speed)) 
				gtab = gt;
			else {
				gtab->itermio.c_cflag = 
				  (gtab->itermio.c_cflag & ~CBAUD) | cbaud;
				gtab->ftermio.c_cflag = 
				  (gtab->ftermio.c_cflag & ~CBAUD) | cbaud;
			}
			settermio(&(gtab->itermio), INITIAL);
		}
	}
}
				

/*
** dologin
**
** print the login banner, get the user's name, and exec login
*/

void dologin()
{
	struct utmp	*utmp;
	int		cbaud, i;
	TERMIO		termio;
	

	for(;;) {
		Nusers = 0;
		setutent();
		while((utmp = getutent())) 
			if(utmp->ut_type == USER_PROCESS) Nusers++;
		endutent();

		cbaud = gtab->itermio.c_cflag & CBAUD;
		for(i=0; speedtab[i].cbaud != cbaud; i++);
		Speed = speedtab[i].speed;

#ifdef ISSUE
		if (gclear && *clrscr) {
			(void) tputs(clrscr, 1, tputc);
		}
		fputc('\r', stdout);

		if(*issue != '/') {
			(void) Fputs(issue, stdout);
			(void) fputs("\r\n", stdout);
		} else if((fp = fopen(issue, "r"))) {
			while(fgets(buf, sizeof(buf), fp))
			  (void) Fputs(buf, stdout);
			(void) fclose(fp);
		}
#endif /* ISSUE */

login_prompt:
		(void) ioctl(STDIN, TCFLSH, 0);
#ifdef FIDO
	if (emsi && (strcmp(emsi,"yes") == 0)) 
		(void) Fputs("**EMSI_REQA77E\r", stdout);
#endif
		(void) Fputs(gtab->login, stdout);
		if(TimeOut > 0) {
			(void) signal(SIGALRM, timeout);
			(void) alarm((unsigned) TimeOut);
		}

		switch(getlogname(&termio, buf, MAXLINE)) {
#ifdef FIDO
			case FIDOCALL:
				(void) signal(SIGALRM, SIG_DFL);
				(void) alarm(0);

				glogin = fido;
				logerr("Fido Call Detected");
#endif /* FIDO */
			case SUCCESS:
				if(buf[0] == '-') {
					printf("\n'-' not allowed as first character of login name\n");
					sleep(5);
					break;
				}
				(void) signal(SIGALRM, SIG_DFL);
				(void) alarm(0);

				if(TimeOut > 0) {
					(void) alarm((unsigned) 0);
					(void) signal(SIGALRM, SIG_DFL);
				}

				termio.c_iflag |= gtab->ftermio.c_iflag;
				termio.c_oflag |= gtab->ftermio.c_oflag;
				termio.c_cflag |= gtab->ftermio.c_cflag;
				termio.c_lflag |= gtab->ftermio.c_lflag;
				termio.c_line |= gtab->ftermio.c_line;
				settermio(&termio, FINAL);
#ifdef SETTERM
				setenv("TERM", term, TRUE);
#endif /* SETTERM */
				debug(D_RUN, "execing login");
				(void) execl(glogin, 
				  "login", buf, (char *)NULL);
				debug(D_RUN, 
				  "exec failed: %s; trying with /bin/sh",
				  strerror(errno));
				(void) execl("/bin/sh", "sh", "-c", glogin,
				  buf, (char *) NULL);
				logerr("exec of %s failed: %s", glogin,
				       strerror(errno));
				exit(FAIL);

			case BADSPEED:
				GtabId = gtab->next_id;
				gtab = gtabvalue(GtabId, G_FORCE);
				settermio(&(gtab->itermio), INITIAL);
				break;

#ifdef WARNCASE
			case BADCASE:
				for(i=0; bad_case[i] != (char *) NULL; i++)
					(void) fputs(bad_case[i], stdout);
				goto login_prompt;
#endif /* WARNCASE */

			case NONAME:
				break;
		}
	}
}


/*
** exit_usage
**
** moan about bad command line options
*/

void exit_usage(code)
int code;
{
	logerr(USAGE, MyName);
	exit(code);
}


/*
** timeout
**
** the user types way too damn slow
*/

void timeout()
{
	TERMIO termio;

	(void) sprintf(MsgBuf, "\nTimed out after %d seconds.\n", TimeOut);
	(void) Fputs(MsgBuf, stdout);

	(void) ioctl(STDIN, TCGETS, &termio);
	termio.c_cflag &= ~CBAUD;
	termio.c_cflag |= B0;
	(void) ioctl(STDIN, TCSETAF, &termio);
	sleep(5);

	exit(1);
}


/*
** tputc
**
** just because
*/

int tputc(c)
char c;
{
	return(fputc(c, stdout));
}


#ifdef SCHED
/*
** schedalarm
**
** signal handler for SCHED
*/

void schedalarm()
{
	debug(D_SCH, "alarm clock caught");
	debug(D_SCH, "... exiting to reinit");
	exit(0);
}
#endif /* SCHED */


#ifdef RBGETTY
/*
** rbalarm
**
** signal handler for RINGBACK
*/

void rbalarm()
{
	debug(D_RB, "alarm clock caught... waited too long for ringback");
	debug(D_RB, "... exiting to reinit");
	exit(0);
}
#endif /* RBGETTY */



/* 
** a bunch of signal handlers for better logging
*/

void shangup()
{
	debug(D_RUN, "Caught HANGUP signal");
	logerr("exiting on HANGUP signal");
	exit(0);
}

void ssegv()
{
	debug(D_RUN, "Caught SEGV signal");
	logerr("Segmentation fault");
	exit(1);
}

void squit()
{
	debug(D_RUN, "Caught QUIT signal");
	logerr("exiting on QUIT signal");
	exit(1);
}

void sterm()
{
	debug(D_RUN, "Caught TERM signal");
	logerr("exiting on TERM signal");
	exit(1);
}