|
root / base / usr / src / cmd / consadm
consadm Plain Text 1353 lines 31.1 KB
   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
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
#
#ident	"%Z%%M%	%I%	%E% SMI"
#
# Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
# cmd/consadm/Makefile
#

PROG=		consadm
MANIFEST=	consadm.xml
SVCMETHOD=	svc-consadm

include ../Makefile.cmd

# Hammerhead: amd64-only
SUBDIRS=	$(MACH64)

ROOTMANIFESTDIR=	$(ROOTSVCSYSTEM)

all	:	TARGET = all
install	:	TARGET = install
clean	:	TARGET = clean
clobber	:	TARGET = clobber
lint	:	TARGET = lint

.KEEP_STATE:

all clean clobber lint:	$(SUBDIRS)

install: $(SUBDIRS) $(ROOTMANIFEST) $(ROOTSVCMETHOD)

check:	$(CHKMANIFEST)

$(SUBDIRS):	FRC
	@cd $@; pwd; $(MAKE) $(TARGET)

FRC:

include ../Makefile.targ
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
# Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
# cmd/consadm/Makefile.com
#

PROG=		consadm

COMMONOBJS=	$(PROG).o utils.o
SRCS=           ../$(PROG).c ../utils.c
OBJS=		$(COMMONOBJS)

include ../../Makefile.cmd

CFLAGS	+=	$(CCVERBOSE)
CERRWARN +=	$(CNOWARN_UNINIT)
CPPFLAGS +=

FILEMODE = 0555

.KEEP_STATE:

all:	$(PROG)

$(PROG): $(OBJS)
	$(LINK.c) -o $@ $(OBJS) $(LDLIBS)
	$(POST_PROCESS)

install: all $(ROOTUSRSBINPROG)
	$(RM) $(ROOTUSRSBIN)/consadmd
	$(LN) $(ROOTUSRSBINPROG) $(ROOTUSRSBIN)/consadmd

clean:
	-$(RM) $(OBJS)

lint:	lint_SRCS

%.o:	../%.c
	$(COMPILE.c) $<

%.o:	./%.c
	$(COMPILE.c) $<

include ../../Makefile.targ
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source. A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#
# Copyright 2025 Hammerhead Project
#

include ../Makefile.com
include $(SRC)/cmd/Makefile.cmd.64

install: all $(ROOTPROG64)
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#include "utils.h"
#include <locale.h>
#include <poll.h>
#include <setjmp.h>
#include <signal.h>
#include <strings.h>
#include <stropts.h>
#include <syslog.h>
#include <sys/sysmsg_impl.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <sys/systeminfo.h>
#include <sys/termios.h>
#include <sys/types.h>

#define	CONSADM			"/usr/sbin/consadm"
#define	CONSADMD		"/usr/sbin/consadmd"
#define	CONSADMLOCK		"/tmp/CoNsAdM.lck"
#define	CONSDAEMON		"consadmd"
#define	MSGLOG			"/dev/msglog"
#define	CONSOLE			"/dev/console"
#define	WSCONS			"/dev/wscons"
#define	CONSCONFIG		"/etc/consadm.conf"
#define	SETCONSOLEPID		"/etc/consadm.pid"

#define	CONFIG			0
#define	UNCONFIG		1
#define	COMMENT			'#'
#define	NEWLINE			'\n'
#define	SPACE			' '
#define	TAB			'	'

#define	E_SUCCESS	0		/* Exit status for success */
#define	E_ERROR		1		/* Exit status for error */
#define	E_USAGE		2		/* Exit status for usage error */
#define	E_NO_CARRIER	3		/* Exit status for no carrier */

/* useful data structures for lock function */
static struct flock fl;
#define	LOCK_EX F_WRLCK

static char usage[] =
	"Usage:	\n"
	"\tconsadm [ -p ] [ -a device ... ]\n"
	"\tconsadm [ -p ] [ -d device ... ]\n"
	"\tconsadm [ -p ]\n";

/* data structures ... */
static char conshdr[] =
	"#\n# consadm.conf\n#"
	"# Configuration parameters for console message redirection.\n"
	"# Do NOT edit this file by hand -- use consadm(8) instead.\n"
	"#\n";
const char *pname;		/* program name */
static sigjmp_buf deadline;

/* command line arguments */
static int display;
static int persist;
static int addflag;
static int deleteflag;

/* function headers */
static void setaux(char *);
static void unsetaux(char *);
static void getconsole(void);
static boolean_t has_carrier(int fd);
static boolean_t modem_support(int fd);
static void setfallback(char *argv[]);
static void removefallback(void);
static void fallbackdaemon(void);
static void persistlist(void);
static int verifyarg(char *, int);
static int safeopen(char *);
static void catch_term(int);
static void catch_alarm(int);
static void catch_hup(int);
static void cleanup_on_exit(int);
static void addtolist(char *);
static void removefromlist(char *);
static int pathcmp(char *, char *);
static int lckfunc(int, int);
typedef void (*sig_handler_t)();
static int getlock(void);

/*
 * In main, return codes carry the following meaning:
 * 0 - successful
 * 1 - error during the command execution
 */

int
main(int argc, char *argv[])
{
	int	index;
	struct	sigaction sa;
	int	c;
	char	*p = strrchr(argv[0], '/');

	if (p == NULL)
		p = argv[0];
	else
		p++;

	pname = p;

	(void) setlocale(LC_ALL, "");
#if	!defined(TEXT_DOMAIN)	/* Should be defined by cc -D */
#define	TEXT_DOMAIN "SYS_TEST"	/* Use this only if it weren't */
#endif
	(void) textdomain(TEXT_DOMAIN);

	if (getuid() != 0)
		die(gettext("must be root to run this program\n"));

	/*
	 * Handle normal termination signals that may be received.
	 */
	sa.sa_handler = SIG_IGN;
	sa.sa_flags = 0;
	(void) sigemptyset(&sa.sa_mask);
	(void) sigaction(SIGHUP, &sa, NULL);
	(void) sigaction(SIGINT, &sa, NULL);
	(void) sigaction(SIGQUIT, &sa, NULL);
	(void) sigaction(SIGTERM, &sa, NULL);

	/*
	 * To make sure persistent state gets removed.
	 */
	sa.sa_handler = cleanup_on_exit;
	sa.sa_flags = 0;
	(void) sigemptyset(&sa.sa_mask);
	(void) sigaction(SIGSEGV, &sa, NULL);
	(void) sigaction(SIGILL, &sa, NULL);
	(void) sigaction(SIGABRT, &sa, NULL);
	(void) sigaction(SIGBUS, &sa, NULL);

	if (strcmp(pname, CONSDAEMON) == 0) {
		fallbackdaemon();
		return (E_SUCCESS);
	}

	if (argc == 1)
		display++;
	else {
		while ((c = getopt(argc, argv, "adp")) != EOF)  {
			switch (c) {
			case 'a':
				addflag++;
				break;
			case 'd':
				deleteflag++;
				break;
			case 'p':
				persist++;
				break;
			default:
				(void) fprintf(stderr, gettext(usage));
				exit(E_USAGE);
				/*NOTREACHED*/
			}
		}
	}

	if (display) {
		getconsole();
		return (E_SUCCESS);
	}
	if (addflag && deleteflag) {
		(void) fprintf(stderr, gettext(usage));
		return (E_ERROR);
	}
	if (addflag) {
		if (optind == argc) {
			(void) fprintf(stderr, gettext(usage));
			return (E_ERROR);
		}
		/* separately check every device path specified */
		for (index = optind; index < argc; index++) {
			if (verifyarg(argv[index], addflag))
				return (E_ERROR);
		}

		for (index = optind; index < argc; index++) {
			setaux(argv[index]);
			if (persist)
				addtolist(argv[index]);
		}

		/*
		 * start/restart daemon based on the auxilary
		 * consoles at this time.
		 */
		setfallback(argv);
		return (E_SUCCESS);
	} else if (deleteflag) {
		if (optind == argc) {
			(void) fprintf(stderr, gettext(usage));
			return (E_ERROR);
		}
		/* separately check every device path specified */
		for (index = optind; index < argc; index++) {
			if (verifyarg(argv[index], 0))
				return (E_ERROR);
		}

		for (index = optind; index < argc; index++) {
			unsetaux(argv[index]);
			if (persist && deleteflag)
				removefromlist(argv[index]);
		}

		/*
		 * kill off daemon and restart with
		 * new list of auxiliary consoles
		 */
		setfallback(argv);
		return (E_SUCCESS);
	} else if (persist) {
		if (optind < argc) {
			(void) fprintf(stderr, gettext(usage));
			return (E_ERROR);
		}

		persistlist();
		return (E_SUCCESS);
	} else {
		(void) fprintf(stderr, gettext(usage));
		return (E_ERROR);
	}
} /* main */

/* for daemon to handle termination from user command */
static void
catch_term(int signal __unused)
{
	exit(E_SUCCESS);
}

/* handle lack of carrier on open */
static void
catch_alarm(int signal __unused)
{
	siglongjmp(deadline, 1);
}

/* caught a sighup */
static void
catch_hup(int signal __unused)
{
	/*
	 * ttymon sends sighup to consadmd because it has the serial
	 * port open.  We catch the signal here, but process it
	 * within fallbackdaemon().  We ignore the signal if the
	 * errno returned was EINTR.
	 */
}

/* Remove persistent state on receiving signal. */
static void
cleanup_on_exit(int signal __unused)
{
	(void) unlink(CONSADMLOCK);
	exit(E_ERROR);
}

/*
 * send ioctl to /dev/sysmsg to route msgs of the device specified.
 */
static void
setaux(char *dev)
{
	int	fd;

	if ((fd = safeopen(SYSMSG)) < 0)
		die(gettext("%s is missing or not a valid device\n"), SYSMSG);

	if (ioctl(fd, CIOCSETCONSOLE, dev) != 0) {
		/*
		 * Let setting duplicate device be warning, consadm
		 * must proceed to set persistence if requested.
		 */
		if (errno == EBUSY)
			die(gettext("%s is already the default console\n"),
			    dev);
		else if (errno != EEXIST)
			die(gettext("cannot get table entry"));
	}
	syslog(LOG_WARNING, "%s: Added auxiliary device %s", CONSADM, dev);

	(void) close(fd);
}

/*
 * Send ioctl to device specified and
 * Remove the entry from the list of auxiliary devices.
 */
static void
unsetaux(char *dev)
{
	int	fd;

	if ((fd = safeopen(SYSMSG)) < 0)
		die(gettext("%s is missing or not a valid device\n"), SYSMSG);

	if (ioctl(fd, CIOCRMCONSOLE, dev) != 0) {
		if (errno == EBUSY)
			die(gettext("cannot unset the default console\n"));
	} else
		syslog(LOG_WARNING, "%s: Removed auxiliary device %s",
		    CONSADM, dev);
	(void) close(fd);
}

static int
getlock(void)
{
	int lckfd;

	if ((lckfd = open(CONSADMLOCK, O_CREAT | O_EXCL | O_WRONLY,
	    S_IRUSR | S_IWUSR)) < 0) {
		if (errno == EEXIST)
			die(gettext("currently busy, try again later.\n"));
		else
			die(gettext("cannot open %s"), CONSADMLOCK);
	}
	if (lckfunc(lckfd, LOCK_EX) == -1) {
		(void) close(lckfd);
		(void) unlink(CONSADMLOCK);
		die(gettext("fcntl operation failed"));
	}
	return (lckfd);
}

static void
addtolist(char *dev)
{
	int	lckfd, fd;
	FILE	*fp, *nfp;
	char	newfile[MAXPATHLEN];
	char	buf[MAXPATHLEN];
	int	len;
	boolean_t	found = B_FALSE;

	/* update file of devices configured to get console msgs. */

	lckfd = getlock();

	/* Open new file */
	(void) snprintf(newfile, sizeof (newfile), "%s%d",
	    CONSCONFIG, (int)getpid());
	if (((fd = creat(newfile, 0644)) < 0) ||
	    ((nfp = fdopen(fd, "w")) == NULL)) {
		(void) close(lckfd);
		(void) unlink(CONSADMLOCK);
		die(gettext("could not create new %s file"), CONSCONFIG);
	}

	/* Add header to new file */
	(void) fprintf(nfp, "%s", conshdr);

	/* Check that the file doesn't already exist */
	if ((fp = fopen(CONSCONFIG, "r")) != NULL) {
		while (fgets(buf, MAXPATHLEN, fp) != NULL) {
			if (buf[0] == COMMENT || buf[0] == NEWLINE ||
			    buf[0] == SPACE || buf[0] == TAB)
				continue;
			len = strlen(buf);
			buf[len - 1] = '\0'; /* Clear carriage return */
			if (pathcmp(dev, buf) == 0) {
				/* they match so use name passed in. */
				(void) fprintf(nfp, "%s\n", dev);
				found = B_TRUE;
			} else
				(void) fprintf(nfp, "%s\n", buf);
		}
	}
	/* User specified persistent settings */
	if (found == B_FALSE)
		(void) fprintf(nfp, "%s\n", dev);

	(void) fclose(fp);
	(void) fclose(nfp);
	(void) rename(newfile, CONSCONFIG);
	(void) close(lckfd);
	(void) unlink(CONSADMLOCK);
}

/* The list in CONSCONFIG gives the persistence capability in the proto */
static void
removefromlist(char *dev)
{
	int	lckfd;
	FILE	*fp, *nfp;
	char	newfile[MAXPATHLEN + 1];
	char	len;
	char	value[MAXPATHLEN + 1];
	boolean_t	newcontents = B_FALSE;

	/* update file of devices configured to get console msgs. */

	lckfd = getlock();

	if ((fp = fopen(CONSCONFIG, "r")) == NULL) {
		(void) close(lckfd);
		(void) unlink(CONSADMLOCK);
		return;
	}

	/* Open new file */
	(void) snprintf(newfile, sizeof (newfile), "%s%d",
	    CONSCONFIG, (int)getpid());
	if ((nfp = fopen(newfile, "w")) == NULL) {
		(void) close(lckfd);
		(void) unlink(CONSADMLOCK);
		die(gettext("cannot create new %s file"), CONSCONFIG);
	}

	/* Add header to new file */
	(void) fprintf(nfp, "%s", conshdr);

	/*
	 * Check whether the path duplicates what is already in the
	 * file.
	 */
	while (fgets(value, MAXPATHLEN, fp) != NULL) {
		/* skip comments */
		if (value[0] == COMMENT || value[0] == NEWLINE ||
		    value[0] == SPACE || value[0] == TAB)
			continue;
		len = strlen(value);
		value[len - 1] = '\0'; /* Clear carriage return */
		if (pathcmp(dev, value) == 0) {
			/* they match so don't write it */
			continue;
		}
		(void) fprintf(nfp, "%s\n", value);
		newcontents = B_TRUE;
	}
	(void) fclose(fp);
	(void) fclose(nfp);
	/* Remove the file if there aren't any auxiliary consoles */
	if (newcontents)
		(void) rename(newfile, CONSCONFIG);
	else {
		(void) unlink(CONSCONFIG);
		(void) unlink(newfile);
	}
	(void) close(lckfd);
	(void) unlink(CONSADMLOCK);
}

static int
pathcmp(char *adev, char *bdev)
{
	struct stat	st1;
	struct stat	st2;

	if (strcmp(adev, bdev) == 0)
		return (0);

	if (stat(adev, &st1) != 0 || !S_ISCHR(st1.st_mode))
		die(gettext("invalid device %s\n"), adev);

	if (stat(bdev, &st2) != 0 || !S_ISCHR(st2.st_mode))
		die(gettext("invalid device %s\n"), bdev);

	if (st1.st_rdev == st2.st_rdev)
		return (0);

	return (1);
}

/*
 * Display configured consoles.
 */
static void
getconsole(void)
{
	int	fd;
	int	bufsize = 0;		/* size of device cache */
	char	*infop, *ptr, *p;	/* info structure for ioctl's */

	if ((fd = safeopen(SYSMSG)) < 0)
		die(gettext("%s is missing or not a valid device\n"), SYSMSG);

	if ((bufsize = ioctl(fd, CIOCGETCONSOLE, NULL)) < 0)
		die(gettext("cannot get table entry\n"));
	if (bufsize == 0)
		return;

	if ((infop = calloc(bufsize, sizeof (char))) == NULL)
		die(gettext("cannot allocate buffer"));

	if (ioctl(fd, CIOCGETCONSOLE, infop) < 0)
		die(gettext("cannot get table entry\n"));

	ptr = infop;
	while (ptr != NULL) {
		p = strchr(ptr, ' ');
		if (p == NULL) {
			(void) printf("%s\n", ptr);
			break;
		}
		*p++ = '\0';
		(void) printf("%s\n", ptr);
		ptr = p;
	}
	(void) close(fd);
}

/*
 * It is supposed that if the device supports TIOCMGET then it
 * might be a serial device.
 */
static boolean_t
modem_support(int fd)
{
	int	modem_state;

	if (ioctl(fd, TIOCMGET, &modem_state) == 0)
		return (B_TRUE);
	else
		return (B_FALSE);
}

static boolean_t
has_carrier(int fd)
{
	int	modem_state;

	if (ioctl(fd, TIOCMGET, &modem_state) == 0)
		return ((modem_state & TIOCM_CAR) != 0);
	else {
		return (B_FALSE);
	}
}

static void
setfallback(char *argv[])
{
	pid_t	pid;
	FILE	*fp;
	char	*cmd = CONSADMD;
	int	lckfd, fd;

	lckfd = getlock();

	/*
	 * kill off any existing daemon
	 * remove /etc/consadm.pid
	 */
	removefallback();

	/* kick off a daemon */
	if ((pid = fork()) == (pid_t)0) {
		/* always fallback to /dev/console */
		argv[0] = cmd;
		argv[1] = NULL;
		(void) close(0);
		(void) close(1);
		(void) close(2);
		(void) close(lckfd);
		if ((fd = open(MSGLOG, O_RDWR)) < 0)
			die(gettext("cannot open %s"), MSGLOG);
		(void) dup2(fd, 1);
		(void) dup2(fd, 2);
		(void) execv(cmd, argv);
		exit(E_SUCCESS);
	} else if (pid == -1)
		die(gettext("%s not started"), CONSADMD);

	if ((fp = fopen(SETCONSOLEPID, "w")) == NULL)
		die(gettext("cannot open %s"), SETCONSOLEPID);
	/* write daemon pid to file */
	(void) fprintf(fp, "%d\n", (int)pid);
	(void) fclose(fp);
	(void) close(lckfd);
	(void) unlink(CONSADMLOCK);
}

/*
 * Remove the daemon that would have implemented the automatic
 * fallback in event of carrier loss on the serial console.
 */
static void
removefallback(void)
{
	FILE	*fp;
	int	pid;

	if ((fp = fopen(SETCONSOLEPID, "r+")) == NULL)
		/* file doesn't exist, so no work to do */
		return;

	if (fscanf(fp, "%d\n", &pid) <= 0) {
		(void) fclose(fp);
		(void) unlink(SETCONSOLEPID);
		return;
	}

	/*
	 * Don't shoot ourselves in the foot by killing init,
	 * sched, pageout, or fsflush.
	 */
	if (pid == 0 || pid == 1 || pid == 2 || pid == 3) {
		(void) unlink(SETCONSOLEPID);
		return;
	}
	/*
	 * kill off the existing daemon listed in
	 * /etc/consadm.pid
	 */
	(void) kill((pid_t)pid, SIGTERM);

	(void) fclose(fp);
	(void) unlink(SETCONSOLEPID);
}

/*
 * Assume we always fall back to /dev/console.
 * parameter passed in will always be the auxiliary device.
 * The daemon will not start after the last device has been removed.
 */
static void
fallbackdaemon(void)
{
	int	fd, sysmfd, ret = 0;
	char	**devpaths;
	pollfd_t	*fds;
	nfds_t	nfds = 0;
	int	index;
	int	pollagain;
	struct	sigaction sa;
	int	bufsize = 0;		/* length of device cache paths */
	int	cachesize = 0;		/* size of device cache */
	char	*infop, *ptr, *p;	/* info structure for ioctl's */

	/*
	 * catch SIGTERM cause it might be coming from user via consadm
	 */
	sa.sa_handler = catch_term;
	sa.sa_flags = 0;
	(void) sigemptyset(&sa.sa_mask);
	(void) sigaction(SIGTERM, &sa, NULL);

	/*
	 * catch SIGHUP cause it might be coming from a disconnect
	 */
	sa.sa_handler = catch_hup;
	sa.sa_flags = 0;
	(void) sigemptyset(&sa.sa_mask);
	(void) sigaction(SIGHUP, &sa, NULL);

	if ((sysmfd = safeopen(SYSMSG)) < 0)
		die(gettext("%s is missing or not a valid device\n"), SYSMSG);

	if ((bufsize = ioctl(sysmfd, CIOCGETCONSOLE, NULL)) < 0)
		die(gettext("cannot get table entry\n"));
	if (bufsize == 0)
		return;

	if ((infop = calloc(bufsize, sizeof (char))) == NULL)
		die(gettext("cannot allocate buffer"));

	if (ioctl(sysmfd, CIOCGETCONSOLE, infop) < 0)
		die(gettext("cannot get table entry\n"));

	ptr = infop;
	while (ptr != NULL) {
		p = strchr(ptr, ' ');
		if (p == NULL) {
			cachesize++;
			break;
		}
		p++;
		cachesize++;
		ptr = p;
	}

	if ((fds = calloc(cachesize, sizeof (struct pollfd))) == NULL)
		die(gettext("cannot allocate buffer"));

	if ((devpaths = calloc(cachesize, sizeof (char *))) == NULL)
		die(gettext("cannot allocate buffer"));

	ptr = infop;
	while (ptr != NULL) {
		p = strchr(ptr, ' ');
		if (p == NULL) {
			if ((fd = safeopen(ptr)) < 0) {
				warn(gettext("cannot open %s, continuing"),
				    ptr);
				break;
			}
			if (!has_carrier(fd)) {
				(void) close(fd);
				warn(gettext(
		    "no carrier on %s, device will not be monitored.\n"),
				    ptr);
				break;
			} else {
				fds[nfds].fd = fd;
				fds[nfds].events = 0;

				if ((devpaths[nfds] =
				    malloc(strlen(ptr) + 1)) == NULL)
					die(gettext("cannot allocate buffer"));

				(void) strcpy(devpaths[nfds], ptr);
				nfds++;
				if (nfds >= cachesize)
					break;
			}
			break;
		}
		*p++ = '\0';

		if ((fd = safeopen(ptr)) < 0) {
			warn(gettext("cannot open %s, continuing"), ptr);
			ptr = p;
			continue;
		}
		if (!has_carrier(fd)) {
			(void) close(fd);
			warn(gettext(
		    "no carrier on %s, device will not be monitored.\n"),
			    ptr);
			ptr = p;
			continue;
		} else {
			fds[nfds].fd = fd;
			fds[nfds].events = 0;

			if ((devpaths[nfds] = malloc(strlen(ptr) + 1)) == NULL)
				die(gettext("cannot allocate buffer"));

			(void) strcpy(devpaths[nfds], ptr);
			nfds++;
			if (nfds >= cachesize)
				break;
		}
		ptr = p;
	}
	(void) close(sysmfd);

	/* no point polling if no devices with carrier */
	if (nfds == 0)
		return;

	for (;;) {
		/* daemon sleeps waiting for a hangup on the console */
		ret = poll(fds, nfds, INFTIM);
		if (ret == -1) {
			/* Check if ttymon is trying to get rid of us */
			if (errno == EINTR)
				continue;
			warn(gettext("cannot poll device"));
			return;
		} else if (ret == 0) {
			warn(gettext("timeout (%d milleseconds) occured\n"),
			    INFTIM);
			return;
		} else {
			/* Go through poll list looking for events. */
			for (index = 0; index < nfds; index++) {
				/* expected result */
				if ((fds[index].revents & POLLHUP) ==
				    POLLHUP) {
					/*
					 * unsetaux console.  Take out of list
					 * of current auxiliary consoles.
					 */
					unsetaux((char *)devpaths[index]);
					warn(gettext(
				    "lost carrier, unsetting console %s\n"),
					    devpaths[index]);
					syslog(LOG_WARNING,
			    "%s: lost carrier, unsetting auxiliary device %s",
					    CONSADM, devpaths[index]);
					free(devpaths[index]);
					devpaths[index] = NULL;
					(void) close(fds[index].fd);
					fds[index].fd = -1;
					fds[index].revents = 0;
					continue;
				}
				if ((fds[index].revents & POLLERR) ==
				    POLLERR) {
					warn(gettext("poll error\n"));
					continue;
				} else if (fds[index].revents != 0) {
					warn(gettext(
					    "unexpected poll result 0x%x\n"),
					    fds[index].revents);
					continue;
				}
			}
			/* check whether any left to poll */
			pollagain = B_FALSE;
			for (index = 0; index < nfds; index++)
				if (fds[index].fd != -1)
					pollagain = B_TRUE;
			if (pollagain == B_TRUE)
				continue;
			else
				return;
		}
	}
}

static void
persistlist(void)
{
	FILE	*fp;
	char	value[MAXPATHLEN + 1];
	int	lckfd;

	lckfd = getlock();

	if ((fp = fopen(CONSCONFIG, "r")) != NULL) {
		while (fgets(value, MAXPATHLEN, fp) != NULL) {
			/* skip comments */
			if (value[0] == COMMENT ||
			    value[0] == NEWLINE ||
			    value[0] == SPACE || value[0] == TAB)
				continue;
			(void) fprintf(stdout, "%s", value);
		}
		(void) fclose(fp);
	}
	(void) close(lckfd);
	(void) unlink(CONSADMLOCK);
}

static int
verifyarg(char *dev, int flag)
{
	struct stat	st;
	int	fd;
	int	ret = 0;

	if (dev == NULL) {
		warn(gettext("specify device(s)\n"));
		ret = 1;
		goto err_exit;
	}

	if (dev[0] != '/') {
		warn(gettext("device name must begin with a '/'\n"));
		ret = 1;
		goto err_exit;
	}

	if ((pathcmp(dev, SYSMSG) == 0) ||
	    (pathcmp(dev, WSCONS) == 0) ||
	    (pathcmp(dev, CONSOLE) == 0)) {
		/* they match */
		warn(gettext("invalid device %s\n"), dev);
		ret = 1;
		goto err_exit;
	}

	if (stat(dev, &st) || ! S_ISCHR(st.st_mode)) {
		warn(gettext("invalid device %s\n"), dev);
		ret = 1;
		goto err_exit;
	}

	/* Delete operation doesn't require this checking */
	if ((fd = safeopen(dev)) < 0) {
		if (flag) {
			warn(gettext("invalid device %s\n"), dev);
			ret = 1;
		}
		goto err_exit;
	}
	if (!modem_support(fd)) {
		warn(gettext("invalid device %s\n"), dev);
		(void) close(fd);
		ret = 1;
		goto err_exit;
	}

	/* Only verify carrier if it's an add operation */
	if (flag) {
		if (!has_carrier(fd)) {
			warn(gettext("failure, no carrier on %s\n"), dev);
			ret = 1;
			goto err_exit;
		}
	}
err_exit:
	return (ret);
}

/*
 * Open the pseudo device, but be prepared to catch sigalarm if we block
 * cause there isn't any carrier present.
 */
static int
safeopen(char *devp)
{
	int	fd;
	struct	sigaction sigact;

	sigact.sa_flags = SA_RESETHAND | SA_NODEFER;
	sigact.sa_handler = catch_alarm;
	(void) sigemptyset(&sigact.sa_mask);
	(void) sigaction(SIGALRM, &sigact, NULL);
	if (sigsetjmp(deadline, 1) != 0)
		return (-1);
	(void) alarm(5);
	/* The sysmsg driver sets NONBLOCK and NDELAY, but what the hell */
	if ((fd = open(devp, O_RDWR | O_NOCTTY | O_NONBLOCK | O_NDELAY)) < 0)
		return (-1);
	(void) alarm(0);
	sigact.sa_flags = 0;
	sigact.sa_handler = SIG_DFL;
	(void) sigemptyset(&sigact.sa_mask);
	(void) sigaction(SIGALRM, &sigact, NULL);
	return (fd);
}

static int
lckfunc(int fd, int flag)
{
	fl.l_type = flag;
	return (fcntl(fd, F_SETLKW, &fl));
}
<?xml version="1.0"?>
<!DOCTYPE service_bundle SYSTEM "/usr/share/lib/xml/dtd/service_bundle.dtd.1">
<!--
 Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
 Use is subject to license terms.

 CDDL HEADER START

 The contents of this file are subject to the terms of the
 Common Development and Distribution License (the "License").
 You may not use this file except in compliance with the License.

 You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 or http://www.opensolaris.org/os/licensing.
 See the License for the specific language governing permissions
 and limitations under the License.

 When distributing Covered Code, include this CDDL HEADER in each
 file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 If applicable, add the following below this CDDL HEADER, with the
 fields enclosed by brackets "[]" replaced with your own identifying
 information: Portions Copyright [yyyy] [name of copyright owner]

 CDDL HEADER END

	NOTE:  This service manifest is not editable; its contents will
	be overwritten by package or patch operations, including
	operating system upgrade.  Make customizations in a different
	file.

	Service manifest for consadm(d).
-->

<service_bundle type='manifest' name='SUNWcsr:consadm'>

<service
	name='system/consadm'
	type='service'
	version='1'>

	<create_default_instance enabled='false' />

	<single_instance />

	<dependency
	    name='usr'
	    grouping='require_all'
	    restart_on='none'
	    type='service'>
		<service_fmri value='svc:/system/filesystem/minimal' />
	</dependency>

	<exec_method
	    type='method'
	    name='start'
	    exec='/lib/svc/method/svc-consadm'
	    timeout_seconds='60' />

	<exec_method
	    type='method'
	    name='stop'
	    exec=':true'
	    timeout_seconds='60' />

	<property_group name='startd' type='framework'>
		<propval name='duration' type='astring' value='transient' />
	</property_group>

	<stability value='Unstable' />

	<template>
		<common_name>
			<loctext xml:lang='C'>
				console monitoring
			</loctext>
		</common_name>

		<documentation>
			<manpage
				title='consadm'
				section='8'
				manpath='/usr/share/man' />
		</documentation>
	</template>
</service>

</service_bundle>
#!/bin/sh
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License, Version 1.0 only
# (the "License").  You may not use this file except in compliance
# with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
#
# Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
# ident	"%Z%%M%	%I%	%E% SMI"

#
# "Start" the "consadm service" by launching consadmd if /etc/consadm.conf
# exists.
#
# Note that these strings are hardcoded into consadm, so there's no benefit to
# keeping them in the repository.
#

. /lib/svc/share/smf_include.sh

if [ -r /etc/consadm.conf ]; then :; else
	echo "No /etc/consadm.conf"
	exit $SMF_EXIT_ERR_CONFIG
fi

/usr/sbin/consadmd &

exit 0
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#include "utils.h"

static const char PNAME_FMT[] = "%s: ";
static const char ERRNO_FMT[] = ": %s\n";

extern const char *pname;

/*PRINTFLIKE1*/
void
warn(const char *format, ...)
{
	int err = errno;
	va_list alist;

	if (pname != NULL)
		(void) fprintf(stderr, gettext(PNAME_FMT), pname);

	va_start(alist, format);
	(void) vfprintf(stderr, format, alist);
	va_end(alist);

	if (strchr(format, '\n') == NULL)
		(void) fprintf(stderr, gettext(ERRNO_FMT), strerror(err));
}

/*PRINTFLIKE1*/
void
die(const char *format, ...)
{
	int err = errno;
	va_list alist;

	if (pname != NULL)
		(void) fprintf(stderr, gettext(PNAME_FMT), pname);

	va_start(alist, format);
	(void) vfprintf(stderr, format, alist);
	va_end(alist);

	if (strchr(format, '\n') == NULL)
		(void) fprintf(stderr, gettext(ERRNO_FMT), strerror(err));

	exit(1);
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright (c) 1998 by Sun Microsystems, Inc.
 * All rights reserved.
 */

#ifndef	_UTILS_H
#define	_UTILS_H

#include <errno.h>
#include <fcntl.h>
#include <libintl.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/param.h>

#ifdef	__cplusplus
extern "C" {
#endif

extern void warn(const char *, ...);
extern void die(const char *, ...);
extern char *strcats(char *, ...);

#ifdef	__cplusplus
}
#endif

#endif	/* _UTILS_H */