This file is indexed.

/usr/bin/maildist is in mailagent 1:3.1-81-4+b1.

This file is owned by root:root, with mode 0o755.

The actual contents of the file can be viewed below.

   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
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
#!/usr/bin/perl
	eval "exec perl -S $0 $*"
		if $running_under_some_shell;

# $Id: maildist.SH 47 2008-06-26 19:18:00Z rmanfredi $
#
#  Copyright (c) 1990-2006, Raphael Manfredi
#  
#  You may redistribute only under the terms of the Artistic License,
#  as specified in the README file that comes with the distribution.
#  You may reuse parts of this distribution only within the terms of
#  that same Artistic License; a copy of which may be found at the root
#  of the source tree for mailagent 3.0.
#
# $Log: maildist.SH,v $
# Revision 3.0.1.5  1996/12/24  14:06:44  ram
# patch45: silently discard hostile addresses
# patch45: added command forwarding support
#
# Revision 3.0.1.4  1995/03/21  12:54:59  ram
# patch35: added pl/cdir.pl to the list of appended files
#
# Revision 3.0.1.3  1994/10/10  10:22:47  ram
# patch19: added various escapes in strings for perl5 support
#
# Revision 3.0.1.2  1994/10/04  17:36:03  ram
# patch17: now uses the email config parameter to send messages to user
# patch17: extended logging to get better error/failure tracking
#
# Revision 3.0.1.1  1993/12/17  08:12:18  ram
# patch4: a regular expression got corrupted by an appliance of itself
#
# Revision 3.0  1993/11/29  13:48:23  ram
# Baseline for mailagent 3.0 netwide release.
#

$mversion = '3.1';
$patchlevel = '0';
$revision = '81';

$prog_name = $0;				# Who I am
$prog_name =~ s|^.*/(.*)|$1|;	# Keep only base name

&read_config;		# First, read configuration file (in ~/.mailagent)

# take job number and command from environment
# (passed by mailagent)
$jobnum = $ENV{'jobnum'};
$fullcmd = $ENV{'fullcmd'};
$pack = $ENV{'pack'};
$path = $ENV{'path'};

&read_dist;			# Read distributions

$dest = shift;		# Who should the system be sent to
$system = shift;	# Which system
$version = shift;	# Which version it is

# A single '-' as first argument stands for return path
$dest = $path if $dest eq '-';

# A single '-' for version means "highest available" version
$version = $Version{$system} if $version eq '-' || $version eq '';

# Full program's name for H table access
$pname = $system . "|" . $version;

$maillist = "To obtain a list of what is available, send me the following mail:

	Subject: Command
	\@SH maillist $path
		^ note the l";

# Silently discard hostile addresses
unless (&addr'valid($dest)) {
	&add_log("FAILED (HOSTILE $dest)") if $loglvl > 1;
	exit 0;
}

if (!$System{$system}) {
	open(MAILER, "|$cf'sendmail $cf'mailopt $path $cf'email") || &nofork;
	print MAILER
"To: $path
Subject: No program called $system
X-Mailer: mailagent [version $mversion-$revision]

I don't know how to send a program called \"$system\".  Sorry.

$maillist

If $cf'name can figure out what you meant, you'll get the program anyway.

-- $prog_name speaking for $cf'user
";
	close MAILER;
	if ($?) {
		&add_log("ERROR cannot report system $system is unknown") if $loglvl;
	} else {
		&add_log("MSG system $system is unknown") if $loglvl > 6;
	}
    &add_log("FAILED (UNKNOWN SYSTEM)") if $loglvl > 1;
    exit 0;
}

if (!$Program{$pname}) {
	open(MAILER, "|$cf'sendmail $cf'mailopt $path $cf'email") || &nofork;
	print MAILER
"To: $path
Subject: No version $version for $system
X-Mailer: mailagent [version $mversion-$revision]

I don't know how to send version $version of $system.  Sorry.

$maillist

If $cf'name can figure out what you meant, you'll get the program anyway.

-- $prog_name speaking for $cf'user
";
	close MAILER;
	if ($?) {
		&add_log("ERROR cannot report system $system $version is unknown")
			if $loglvl;
	} else {
		&add_log("MSG system $system version $version is unknown")
			if $loglvl > 6;
	}
    &add_log("FAILED (BAD VERSION NUMBER)") if $loglvl > 1;
    exit 0;
}

# Has the user made a request for an old version (patch only) ?
if ($Patch_only{$pname}) {
	# It is required that patch only systems have a version number
	&abort("old system has no version number") if $version eq '';
	open(MAILER, "|$cf'sendmail $cf'mailopt $path $cf'email") || &nofork;
	print MAILER
"To: $path
Subject: System $system $version is obsolete
X-Mailer: mailagent [version $mversion-$revision]

I can't send you version $version of $system. Sorry.

This version appears to be an old one, and only patches are available.
The up-to-date version for $system is $Version{$system}.

$maillist

If $cf'name can figure out what you meant, he may send you the latest version.

-- $prog_name speaking for $cf'user
";
	close MAILER;
	if ($?) {
		&add_log("ERROR cannot report system $system $version is obsolete")
			if $loglvl;
	} else {
		&add_log("MSG system $system $version is obsolete") if $loglvl > 6;
	}
    &add_log("FAILED (PATCH ONLY VERSION)") if $loglvl > 1;
    exit 0;
}

# If the request is not the most recent version, warn the user.
if ($version < $Version{$system}) {
	open(MAILER, "|$cf'sendmail $cf'mailopt $path $cf'email") || &nofork;
	print MAILER
"To: $path
Subject: Version $version of $system is an old one
X-Mailer: mailagent [version $mversion-$revision]

You asked for version $version of $system.

This version appears to be an old one, but it is sill available, and
I am currently processing your request. However, I wanted to let you
know that the up-to-date version for $system is $Version{$system}.

$maillist

Unless you receive an error message telling you otherwise, I am sending
you version $version of $system. You may also request for the new version
right now if you wish.

-- $prog_name speaking for $cf'user
";
	close MAILER;
	if ($?) {
		&add_log("ERROR cannot report $system $version is old") if $loglvl;
	} else {
		&add_log("MSG system $system $version is old") if $loglvl > 6;
	}
}

# Create a temporary directory
$tmp = "$cf'tmpdir/dmd$$";
mkdir($tmp, 0700);

# Need to unarchive the distribution
if ($Archived{$pname}) {
	# Create a temporary directory for distribution
	$tmp_loc = "$cf'tmpdir/dmdl$$";
	mkdir($tmp_loc, 0700);
	$location =
		&unpack($Location{$pname}, $tmp_loc, $Compressed{$pname});
} else {
	$location = $Location{$pname};
}

# Go to the package root directory and check for possible forwarding...
chdir($location) || &abort("cannot chdir to $location: $!");
&check_forward;			# Returns only if command is not forwarded

# We are now in the place. Look for a MANIFEST file. If none, we will
# send *everything* held, RCS sub-directories and executable/object files
# excepted.

$manifest = '';
$tmp_list = '';

if (-f 'MANIFEST') {
	$manifest = "$location/MANIFEST";
} else {
	$tmp_list = "$cf'tmpdir/mdlist$$";
	open(FIND, "find . -type f -print | sort |") ||
		&abort("cannot run find");
	open(LIST, ">$tmp_list") ||
		&abort("cannot create $tmp_list");
	while (<FIND>) {
		chop;
		s|\./||;
		next if (m|^U/| && -f '.package');	# Skip units if meta-configured
		next if m|^RCS/|;			# Skip RCS files
		next if m|/RCS/|;
		next if m|,v$|;
		next if m|bugs/|;			# Skip bugs files (patches and al.)
		next if m|^\.#|;			# Skip [marked for deletion] files
		next if m|/\.#|;
		next if m|\.o$|;			# Skip object files
		next if m|core$|;			# Skip core files
		next if (-x $_ && -B $_);	# Skip binaries
		print LIST $_,"\n";			# Keep that file
	}
	close FIND;
	close LIST;
	$manifest = $tmp_list;
}

&add_log("manifest is in $manifest") if $loglvl > 19;

# If distribution is maintained by dist 3.0 (at least), there is a .package
# file in there and we can invoke makedist. Otherwise, we have to do it by
# hand...

if (-f '.package') {
	system "makedist -c $tmp -f $manifest";
	&abort("cannot run makedist -c $tmp") if $?;
} else {
	&makedist;
}

$subject = "$system";
$subject .= " $version" if $version ne '0';
$subject .= " package";
&sendfile($dest, $tmp, $pack, $subject);
&clean_tmp;

exit 0;		# Ok

# Now for each file in manifest, look if there is an
# RCS file associated with it. If so, check out either
# the 'lastpat' version or the highest version on the
# default branch, provided that the file does not exists
# in checked-out form. Otherwise, only run co if 'lastpat'
# is defined.
sub makedist {
	chdir $tmp || &abort("cannot chdir to $tmp");
	open(MANI, $manifest) || &abort("cannot open $manifest");
	while (<MANI>) {
		next if /^--/;
		s|^\s*||;						# Remove leading spaces
		($file,$foo) = split;			# Save filename, discard comments
		next if (-d "$location/$file");	# Skip directories
		next if ($file =~ /^\s*$/);		# Skip blank lines
		# Extract dirname and basename
		($dir, $base) = ('', $file)
			unless ($dir, $base) = ($file =~ m|(.*/)(.*)|);
		$logmsg = '';				# String to add to log message
		$rcsfile = 'blurfl';
		$rcsfile = "$location/$file,v" if (-f "$location/$file,v");
		$rcsfile = "$location/${dir}RCS/$base,v"
			if (-f "$location/${dir}RCS/$base,v");
		next unless -f "$location/$file" || -f "$rcsfile";	# Skip unexisting files
		&makedir($dir) unless $dir eq '';
		open(COPY, ">$file") || &abort("cannot create $file");
		if ($rcsfile ne '') {
			$rlog = `rlog $rcsfile 2>&1`;
			($revs) = ($rlog =~ /lastpat: (\d+)/);
			if (!$revs) {
				# Symbol 'lastpat' is not defined
				# If file exists, open it. Otherwise, run co
				if (-f "$location/$file") {
					$logmsg = " (lastpat undefined)";
					$origfile = "$location/$file";
					open(FILE, $origfile) ||
						&abort("cannot open $origfile");
				} else {
					$logmsg = " (co but no lastpat)";
					$origfile = $rcsfile;
					open(FILE, "co -q -p $rcsfile |") ||
						&abort("cannot run co on $rcsfile");
				}
			} else {
				# Symbol 'lastpat' is defined
				$logmsg = " (co lastpat)";
				$origfile = $rcsfile;
				open(FILE, "co -q -p -rlastpat $rcsfile |") ||
					&abort("cannot run co on $rcsfile");
			}
		} else {
			$origfile = "$location/$file";
			open(FILE, "$location/$file") ||
				&abort("cannot open $location/$file");
		}
		while (<FILE>) {
			# Use Lock[e]r, not Locker, since we might apply this on
			# ourself one day and get corrupted...
			s|Lock[e]r:.*\$|\$|;      # Remove locker mark
			(print COPY) || &abort("copy error: $!");
		}
		close(FILE) || &abort("copy error: $!");
		close COPY;
		&add_log("copied $file$logmsg") if $loglvl > 19;

		# If file is executable, change its permissions
		if (-x $origfile) {
			chmod 0755, $file;
		} else {
			chmod 0644, $file;
		}
	}
}

sub clean_tmp {
	# Do not stay in the directories we are removing...
	chdir $cf'home;
	if ($tmp ne '') {
		system '/bin/rm', '-rf', $tmp;
		&add_log("removed dir $tmp") if $loglvl > 19;
	}
	if ($Archived{$pname}) {
		system '/bin/rm', '-rf', $tmp_loc;
		&add_log("removed dir $tmp_loc") if $loglvl > 19;
	}
	unlink $tmp_list if $tmp_list ne '';
}

# Emergency exit with clean-up
sub abort {
	local($reason) = shift(@_);		# Why we are exiting
	&clean_tmp;
	&fatal($reason);
}

# Report error while forking a sendmail process
sub nofork {
	&add_log("SYSERR fork: $!") if $loglvl;
	&add_log("ERROR cannot launch $cf'sendmail") if $loglvl;
}

# Make directories for files
# E.g, for /usr/lib/perl/foo, it will check for all the directories /usr,
# /usr/lib, /usr/lib/perl and make them if they do not exist.
# Note: default mode is now 0777 since we have an umask config parameter.
sub makedir {
	local($dir, $mode) = @_;	# directory name, mode (optional)
	local($parent);
	$mode = 0777 unless defined $mode;
	$dir =~ s|/$||;				# no trailing / or we'll try to make dir twice
	if (!-d $dir && $dir ne '') {
		# Make parent dir first
		&makedir($parent, $mode) if ($parent = $dir) =~ s|(.*)/.*|$1|;
		if (mkdir($dir, $mode)) {
			&add_log("creating directory $dir") if $loglvl > 19;
		} else {
			&add_log("ERROR cannot create directory $dir: $!")
				if $loglvl > 1;
		}
	}
}

# In case of fatal error, the program does not simply die
# but also records the failure in the log.
sub fatal {
	local($reason) = @_;			# Why did we get here ?
	&add_log("FAILED ($reason)") if $loglvl > 0;
	die "$prog_name: $reason\n";
}

# Emergency signal was caught
sub emergency {
	local($sig) = @_;			# First argument is signal name
	&fatal("trapped SIG$sig");
}

# Add an entry to logfile
# There is no need to lock logfile as print is sandwiched betweeen
# an open and a close (kernel will flush at the end of the file).
sub add_log {
	# Indirection needed, so that we may remap add_log on stderr_log via a
	# type glob assignment.
	&usrlog'write_log($cf'logfile, $_[0], undef);
}

# When mailagent is used interactively, log messages are also printed on
# the standard error.
# NB: this function is not called directly, but via a type glob *add_log.
sub stderr_log {
	print STDERR "$prog_name: $_[0]\n";
	&usrlog'write_log($cf'logfile, $_[0], undef);
}

# Routine used to emit logs when no logging has been configured yet.
# As soon as a valid configuration has been loaded, logs will also be
# duplicated into the logfile. Used solely by &cf'setup.
# NB: this function is not called directly, but via a type glob *add_log.
sub stdout_log {
	print STDOUT "$prog_name: $_[0]\n";
	&usrlog'write_log($cf'logfile, $_[0], undef) if defined $cf'logfile;
}

#
# User-defined log files
#

package usrlog;

# Record a new logfile by storing its pathname in the %Logpath hash table
# indexed by names and the carbon-copy flag in the %Cc table.
sub new {
	local($name, $path, $cc) = @_;
	return if defined $Logpath{$name};	# Logfile already recorded
	return if $name eq 'default';		# Cannot redefined defaul log
	$path = "$cf'logdir/$path" unless $path =~ m|^/|;
	$Logpath{$name} = $path;			# Where logfile should be stored
	$Cc{$name} = $cc ? 1 : 0;			# Should we cc the default logfile?
	$Map{$path} = $name;				# Two-way hash table
}

# Delete user-defined logfile.
sub delete {
	local($name) = @_;
	return unless defined $Logpath{$name};
	local($path) = $Logpath{$name};
	delete $Logpath{$name};
	delete $Cc{$name};
	delete $Map{$path};
}

# User-level logging main entry point
sub main'usr_log {
	local($name, $message) = @_;	# Logfile name and message to be logged
	local($file);
	$file = ($name eq 'default' || !defined $Logpath{$name}) ?
		$cf'logfile : $Logpath{$name};
	&write_log($file, $message, $Cc{$name});
}

# Log message into logfile, using jobnum to identify process.
sub write_log {
	local($file, $msg, $cc) = @_;	# Logfile, message to be logged, cc flag
	local($date);
	local($log);

	return unless length $file;

	local ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
		localtime(time);
	$date = sprintf("%.2d/%.2d/%.2d %.2d:%.2d:%.2d",
		$year % 100,++$mon,$mday,$hour,$min,$sec);
	$log = $date . " $'prog_name\[$'jobnum\]: $msg\n";

	# If we cannot append to the logfile, first check whether it is the default
	# logfile or not. If it is not, then add a log entry to state the error in
	# the default log and then delete that user logname entry, assuming the
	# fault we get is of a permanent nature and not an NFS failure for instance.

	unless (open(LOGFILE, ">>$file")) {
		if ($file ne $cf'logfile) {
			local($name) = $Map{$file};	# Name under which it was registered
			&'add_log("ERROR cannot append to $name logfile $file: $!")
				if $'loglvl > 1;
			&'add_log("NOTICE removing logging to $file") if $'loglvl > 6;
			&delete($Map{$file});
			$cc = 1;				# Force logging to default file
		} else {					# We were already writing to default log
			return;					# Cannot log message at all
		}
	}

	print LOGFILE $log;
	close LOGFILE;

	# If $cc is set, a copy of the same log message (same time stamp guaranteed)
	# is made to the default logfile. If called with $file set to that default
	# logfile, $cc will be undef by construction.

	if ($cc) {
		open(LOGFILE, ">>$cf'logfile");
		print LOGFILE $log;
		close LOGFILE;
	}
}

package main;

package cf;

# This package is responsible for keeping track of the configuration variables.

# Read configuration file (usually in ~/.mailagent)
sub main'read_config {
	local($file) = @_;				# where config file is located
	local($_);
	$file = '~/.mailagent' unless $file;
	local($myhome) = $ENV{'HOME'};	# must be correctly set by filter
	$file =~ s/~/$myhome/;			# ~ substitution
	local($main'config) = $file;	# Save it: could be modified by config
	open(CONFIG, "$file") ||
		&'fatal("can't open config file $file");
	local($config) = ' ' x 2000;	# pre-extend to avoid realloc()
	$config = '';
	while (<CONFIG>) {
		next if /^[ \t]*#/;			# skip comments
		next if /^[ \t]*\n/;		# skip empy lines
		s/([^\\](\\\\)*)@/$1\\@/g;	# escape all un-escaped @ in string
		$config .= $_;
	}
	&parse($config) || &'fatal('bad configuration');
	close CONFIG;

	# Security checks, pending of those performed by the C filter. They are
	# somewhat necessary, even though the mailagent does not run setuid
	# (because anybody may activate the mailagent for any user by sending him
	# a mail, and world writable configuration files makes the task too easy
	# for a potential hacker). The tests are performed once the configuration
	# file has been parsed, so logging of fatal errors may occur.

	local($unsecure) = 0;

	$unsecure++ unless &'file_secure($'config, 'config');
	$unsecure++ unless &'file_secure($rules, 'rule');
	&'fatal("unsecure configuration!") if $unsecure;

	return unless -f "$rules";		# No rule file
}

# Parse config file held in variable and return 1 if ok, 0 for errors
sub parse {
	local($config) = @_;
	return 1 unless defined $config;
	local($eval) = ' ' x 1000;		# Pre-extend
	local($myhome) = $ENV{'HOME'};	# must be correctly set by filter
	local($var, $value);
	local($_);
	$eval = '';
	foreach (split(/\n/, $config)) {
		if (/^[ \t]*([^ \t\n:\/]*)[ \t]*:[ \t]*([^#\n]*)/) {
			$var = $1;
			$value = $2;
			$value =~ s/\s*$//;						# remove trailing spaces
			$eval .= "\$$var = \"$value\";\n";
			$eval .= "\$$var =~ s|~|\$myhome|g;\n";	# ~ substitution
		}
	}
	eval $eval;			# evaluate configuration parameters within package

	if ($@ ne '') {				# Parsing error detected
		local($error) = $@;		# Logged error
		$error = (split(/\n/, $error))[0];		# Keep only first line
		# Dump error message on stderr, as well as faulty configuration file.
		# The original is restored out of the perl form to avoid surprise.
		$eval =~ s/^\$.* =~ s\|~\|.*\n//gm;		# Remove added ~ substitutions
		$eval =~ s/^\$//gm;						# Remove leading '$'
		$eval =~ s/ = "(.*)";/: $1/gm;			# Keep only variable value
		chop($eval);
		print STDERR <<EOM;
**** Syntax error in configuration:
$error

---- Begin of Faulty Configuration
$eval
---- End of Faulty Configuration

EOM
		&'add_log("syntax error in configuration: $error") if $'loglvl > 1;
		return 0;
	}

	# Define the mailagent parameters from those in config file
	$logfile = $logdir . "/$log";
	$seqfile = $spool . "/$seq";
	$hashdir = $spool . "/$hash";
	$main'loglvl = int($level);		# This one is visible in the main package
	$main'track_all = 1 if $track =~ /on/i;		# Option -t set by config
	$sendmail = $'mailer if $sendmail eq '';	# No sendmail program specified
	$sendnews = $'inews if $sendnews eq '';		# No news posting program
	$mailopt = '-odq -i' if $mailopt eq '' && $sendmail =~ /sendmail/;

	# Backward compatibility -- RAM, 25/04/94
	$fromesc = 'ON' unless defined $fromesc;	# If absent from ~/.mailagent
	$lockmax = 20 unless defined $lockmax;
	$lockdelay = 2 unless defined $lockdelay;
	$lockhold = 3600 unless defined $lockhold;
	$queuewait = 60 unless defined $queuewait;
	$queuehold = 1800 unless defined $queuehold;
	$queuelost = 86400 unless defined $queuelost;
	$runmax = 3600 unless defined $runmax;
	$umask = 077 unless defined $umask;
	$email = $user unless defined $email;
	$compspec = "$spool/compressors" unless defined $compspec;
	$comptag = 'gzip' unless defined $comptag;
	$locksafe = 'OFF' unless defined $locksafe;
	$execsafe = 'OFF' unless defined $execsafe;

	# For backward compatibility, we force a .lock locking on mailboxes.
	# For system ones (name = login), there's no problem because the lock
	# file is still under the 14 characters limit. If mail is saved in folders
	# whose name is longer, there might be problems though. There's little we
	# can do about it here, lest they choose an alternate locking name.
	# Note that mailagent's $lockext global variable setting depends on the
	# fact that the target system supports flexible filenames or not, so only
	# mailbox locking is a problem -- RAM, 18/07/95

	$mboxlock = '%f.lock' unless defined $mboxlock;

	# Backward compatibility -- RAM, 17/03/2001
	$domain = $main::hiddennet || $main::mydomain unless defined $domain;
	$hidenet = $main::hiddennet eq '' ? 'OFF' : 'ON' unless defined $hidenet;

	$umask = oct($umask) if $umask =~ /^0/;	 # Translate umask into decimal
	$domain =~ s/^\.*//;					 # Strip leading '.'

	# Update @INC perlib search path with the perlib variable. Paths not
	# starting by a '/' are supposed to be under the mailagent private lib
	# directory.

	local(%seen);		# Avoid dups in @INC (might be called more than once)

	foreach (@INC) { $seen{$_}++; }

	if (defined $perlib) {
		foreach (split(':', $perlib)) {
			s/^~/$home/;
			$_ = $'privlib . '/' . $_ unless m|^/|;
			push(@INC, $_) unless $seen{$_}++;
		}
	}

	1;		# Ok
}

package main;

# Expands an archive's name
sub expand {
	local($path) = shift;		# The archive
	# Look for extension of base path (eg: .cpio.Z)
	local(@fullpath) = <${path}.*>;
	if (-1 == $#fullpath) {
		&clean_tmp;
		&fatal("no archive file");
	}
	$path = $fullpath[0];		# Name with archive extension
}

# Unpack(path,dir,flag) restores archive `path' into `dir'
# and returns the location of the main directory.
sub unpack {
	local($path) = shift;		# The archive
	local($dir) = shift;		# Storage place
	local($compflag) = shift;	# Flag for compression (useful for short names)
	local($unpack) = "";		# Will hold the restore command
	$path = &expand($path);		# Name with archive extension
	&add_log("archive is $path") if $loglvl > 19;
	# First determine wether it is compressed
	if ($compflag) {
		$unpack = "zcat | ";
	}
	# Cpio or tar ?
	if ($path =~ /\.tar/) {
		$unpack .= "tar xof -";
	} else {
		$unpack .= "cpio -icmd";
	}
	system "< $path (cd $dir; $unpack)";
	$path =~ s|.*/([\w-]+)|$1|;	# Keep only basename
	local ($stat) = $?;			# Return status
	if ($stat) {
		&clean_tmp;
		&fatal("unable to unpack $path");
	}
	&add_log("unpacked $path with \"$unpack\"") if $loglvl > 12;

	# The top level directory is the only file in $dir
	local(@top) = <${dir}/*>;
	if ($#top < 0) {
		&clean_tmp;
		&fatal("$prog_name: no top-level dir for $path");
	}
	if ($#top > 0) {
		&add_log("WARNING more than one file in $dir") if $loglvl > 4;
	}
	&add_log("top-level dir for $path is $top[0]") if $loglvl > 19;
	$top[0];		# Top-level directory
}

# Send a set of files
sub sendfile {
	local($dest, $cf'tmpdir, $pack, $subject) = @_;
	&add_log("sending dir $cf'tmpdir to $dest, mode $pack") if $loglvl > 9;

	# A little help message
	local($mail_help) = "Detailed intructions can be obtained by:

	Subject: Command
	\@SH mailhelp $dest";

	# Go to tmpdir where files are stored
	chdir $cf'tmpdir || &abort("NO TMP DIRECTORY");

	# Build a list of files to send
	local($list) = "";		# List of plain files
	local($dlist) = "";		# List with directories (for makekit)
	local($nbyte) = 0;
	local($nsend) = 0;
	open(FIND, "find . -print |") || &abort("CANNOT RUN FIND");
	while (<FIND>) {
		chop;
		next if $_ eq '.';		# Skip current directory `.'
		s|^\./||;
		$dlist .= $_ . " ";		# Save file/dir name
		if (-f $_) {			# If plain file
			$list .= $_ . " ";	# Save plain file
			$nsend++;			# One more file to send
			($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,
				$blksize,$blocks) = stat($_);
			$nbyte += $size;	# Update total size
		}
	}
	close FIND;

	&abort("NO FILE TO SEND") unless $nsend;
	if ($nsend > 1) {
		&add_log("$nsend files to pack ($nbyte bytes)") if $loglvl > 9;
	} else {
		&add_log("1 file to pack ($nbyte bytes)") if $loglvl > 9;
	}

	# Pack files
	if ($pack =~ /kit/) {
		system "kit -n Part $list" || &abort("CANNOT KIT FILES");
		$packed = "kit";
	} elsif ($pack =~ /shar/) {
		# Create a manifest, so that we can easily run maniscan
		# Leave a PACKNOTES file with non-zero length if problems.
		local($mani) = $dlist;
		$mani =~ s/ /\n/g;
		local($packlist) = "pack.$$";	# Pack list used as manifest
		if (open(PACKLIST, ">$packlist")) {
			print PACKLIST $mani;
			close PACKLIST;
			system 'maniscan', "-i$packlist",
				"-o$packlist", '-w0', '-n', '-lPACKNOTES';
			&add_log("ERROR maniscan returned non-zero status")
				if $loglvl > 5 && $?;
			if (-s 'PACKNOTES') {		# Files split or uu-encoded
				system 'makekit', "-i$packlist", '-t',
					"Now run 'sh PACKNOTES'." || &abort("CANNOT SHAR FILES");
			} else {
				system 'makekit', "-i$packlist" || &abort("CANNOT SHAR FILES");
			}
		} else {
			&add_log("ERROR cannot create packlist") if $loglvl > 5;
			system "makekit $dlist" || &abort("CANNOT SHAR FILES");
		}
		$packed = "shar";
	} else {
		if ($nbyte > $cf'maxsize) {		# Defined in ~/.mailagent
			system "kit -M -n Part $list" || &abort("CANNOT KIT FILES");
			$packed = "minikit";		# The minikit is included
		} else {
			# Try with makekit first
			if (system "makekit $dlist") {	# If failed
				system "kit -M -n Part $list" || &abort("CANNOT KIT FILES");
				$packed = "minikit";	# The minikit is included
			} else {
				$packed = "shar";
			}
		}
	}

	# How many parts are there ?
	@parts = <Part*>;
	$npart = $#parts + 1;		# Number of parts made
	&abort("NO PART TO SEND -- $packed failed") unless $npart;
	if ($npart > 1) {
		&add_log("$npart $packed parts to send") if $loglvl > 19;
	} else {
		&add_log("$npart $packed part to send") if $loglvl > 19;
	}

	# Now send the parts
	$nbyte = 0;				# How many bytes do we send ?
	$part_num = 0;
	$signal="";				# To signal parts number if more than 1
	local($partsent) = 0;	# Number of parts actually sent
	local($bytesent) = 0;	# Amount of bytes actually sent
	foreach $part (@parts) {
		($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,
			$blksize,$blocks) = stat($part);
		$nbyte += $size;	# Update total size

		&add_log("dealing with $part ($size bytes)") if $loglvl > 19;

		# See if we need to signal other parts
		$part_num++;			# Update part number
		if ($npart > 1) {
			$signal=" (Part $part_num/$npart)";
		}

		# Send part
		open(MAILER, "|$cf'sendmail $cf'mailopt $dest");
		print MAILER
"To: $dest
Subject: $subject$signal
Precedence: bulk
X-Mailer: mailagent [version $mversion-$revision]

Here is the answer to your request:

	$fullcmd


";
		if ($packed eq 'minikit') {		# Kit with minikit included
			print MAILER
"This is a kit file. It will be simpler to unkit it if you own the kit
package (latest patchlevel), but you can use the minikit provided with
this set of file (please see instructions provided by kit itself at the
head of each part). If you wish to get kit, send me the following mail:

";
		} elsif ($packed eq 'kit') {	# Plain kit files
			print MAILER
"This is a kit file. You need the kit package (latest patchlevel) to
unkit it. If you do not have kit, send me the following mail:

";
		}
		if ($packed =~ /kit/) {		# Kit parts
			print MAILER
"	Subject: Command
	\@PACK shar
	\@SH maildist $dest kit -

and you will get the latest release of kit as shell archives.

$mail_help

";
			# Repeat instructions which should be provided by kit anyway
			if ($npart > 1) {
				print MAILER
"Unkit:	Save this mail into a file, e.g. \"foo$part_num\" and wait until
	you have received the $npart parts. Then, do \"unkit foo*\". To see
	what will be extracted, you may wish to do \"unkit -l foo*\" before.
";
			} else {
				print MAILER
"Unkit:	Save this mail into a file, e.g. \"foo\". Then do \"unkit foo\". To see
	what will be extracted, you may wish to do \"unkit -l foo\" before.
";
			}
			# If we used the minikit, signal where instruction may be found
			if ($packed eq 'minikit') {
				print MAILER
"	This kit archive also contains a minikit which will enable you to
	extract the files even if you do not have kit. Please follow the
	instructions kit has provided for you at the head of each part. Should
	the minikit prove itself useless, you may wish to get kit.
";
			}
		} else {			# Shar parts
			print MAILER
"This is a shar file. It will be simpler to unshar it if you own the Rich Salz's
cshar package. If you do not have it, send me the following mail:

	Subject: Command
	\@PACK shar
	\@SH maildist $dest cshar 3.0

and you will get cshar as shell archives.

$mail_help

";
			if (-s 'PACKNOTES') {		# Problems detected by maniscan
				print MAILER
"
Warning:
	Some minor problems were encountered during the building of the
	shell archives. Perhaps a big file has been split, a binary has been
	uu-encoded, or some lines were too long. Once you have unpacked the
	whole distribution, see file PACKNOTES for more information. You can
	run it through sh by typing 'sh PACKNOTES' to restore possible splited
	or encoded files.

";
			}
			if ($npart > 1) {
				print MAILER
"Unshar: Save this mail into a file, e.g. \"foo$part_num\" and wait until
	you have received the $npart parts. Then, do \"unshar -n foo*\". If you
	do not own \"unshar\", edit the $npart files and remove the mail header
	by hand before feeding into sh.
";
			} else {
				print MAILER
"Unshar: Save this mail into a file, e.g. \"foo\". Then do \"unshar -n foo\". If
	you do not own \"unshar\", edit the file and remove the mail header by
	hand before feeding into sh.
";
			}
		}
		print MAILER
"
-- $prog_name speaking for $cf'user


";
		open(PART, $part) || &abort("CANNOT OPEN $part");
		while (<PART>) {
			print MAILER;
		}
		close PART;
		close MAILER;
		if ($?) {
			&add_log("ERROR couldn't send $size bytes to $dest")
				if $loglvl > 1;
		} else {
			&add_log("SENT $size bytes to $dest") if $loglvl > 2;
			$partsent++;
			$bytesent += $size;
		}
	}

	# Prepare log message
	local($partof) = "";
	local($byteof) = "";
	local($part);
	local($byte);
	if ($partsent > 1) {
		$part = "parts";
	} else {
		$part = "part";
	}
	if ($bytesent > 1) {
		$byte = "bytes";
	} else {
		$byte = "byte";
	}
	if ($partsent != $npart) {
		$partof = " (of $npart)";
		$byteof = "/$nbyte";
	}
	&add_log(
		"SENT $partsent$partof $packed $part ($bytesent$byteof $byte) to $dest"
	) if $loglvl > 4;
}

# In case something got wrong
# We call the clean_tmp routine, which must be defined in the
# main program that will use abort.
sub abort {
	local($reason) = shift;		# Why do we abort ?
	local($cmd) = $fullcmd =~ /^(\S+)/;
	open(MAILER, "|$cf'sendmail $cf'mailopt $path $cf'email");
	print MAILER
"To: $path
Subject: $cmd failed
X-Mailer: mailagent [version $mversion-$revision]

Sorry, the $prog_name command failed while sending files.

Your command was: $fullcmd
Error message I got:

	>>>> $reason <<<<

If $cf'name can figure out what you meant, he may answer anyway.

-- $prog_name speaking for $cf'user
";
	close MAILER;
	&add_log("FAILED ($reason)") if $loglvl > 1;
	&clean_tmp;
	exit 0;			# Scheduled error
}

# Read a distribution file and fill in data structures for
# the query functions. All the data are stored in associative
# arrays, indexed by the system's name and version number.
# Associative arrays are:
#
# name          indexed by       information
#
# %Program      name + version   have we seen that line ?
# %System       name             is name a valid system ?
# %Version      name             latest version for system
# %Location		name + version   location of the distribution
# %Archived     name + version   is distribution archived ?
# %Compressed   name + version   is archive compressed ?
# %Patch_only   name + version   true if only patches delivered
# %Maintained   name + version   true if distribution is maintained
# %Patches      name + version   true if official patches available
#
# For systems with a version of '---' in the file, the version
# for accessing the data has to be a "0" string.
#
# Expected format for the distribution file:
#     system version location archive compress patches
#
# The `archive', `compress' and `patches' fields can take one
# of the following states: "yes" and "no". An additional state
# for `patches' is "old", which means that only patches are
# available for the version, and not the distribution. Another is
# "patch" which means that official patches are available.
# All these states can be abbreviated with the first letter.
#
sub read_dist {
	local($fullname);
	open(DIST, "$cf'distlist") ||
		&fatal("cannot open distribution file");
	while (<DIST>) {
		next if /^\s*#/;	# skip comments
		next if /^\s*$/;	# skip empty lines
		next unless s/^\s*(\w+)\s+([.\-0-9]+)//;
		$fullname = $1 . "|" . ($2 eq '---'? "0" : $2);
		if (defined $Program{$fullname}) {
			&add_log("WARNING duplicate distlist entry $1 $2 ignored")
				if $loglvl > 5;
			next;
		}
		$Program{$fullname}++;
		$Version{$1} = ($2 eq '---' ? "0" : $2) unless
			defined($System{$1}) && $Version{$1} > ($2 eq '---' ? "0":$2);
		$System{$1}++;
		unless (/^\s*(\S+)\s+(\w+)\s+(\w+)\s+(\w+)/) {
			&add_log("WARNING bad system description line $.")
				if $loglvl > 5;
			next;	# Ignore, but it may corrupt further processing
		}
		local($location) = $1;
		local($archive) = $2;
		local($compress) = $3;
		local($patch) = $4;
		$location =~ s/~\//$cf'home\//;		# ~ expansion
		$Location{$fullname} = $location;
		$Archived{$fullname}++ if $archive =~ /^y/;
		$Compressed{$fullname}++ if $compress =~ /^y/;
		$Patch_only{$fullname}++ if $patch =~ /^o/;
		$Maintained{$fullname}++ if $patch =~ /^y|o/;
		$Patches{$fullname}++ if $patch =~ /^p/;
	}
	close DIST;
}

# A file "secure" if it is owned by the user and not world writable. Some key
# file within the mailagent have to be kept secure or they might compromise the
# security of the user account.
#
# Additionally, for 'root' users or if the 'secure' parameter in the config
# file is set to ON, checks are made for group writable files and suspicious
# directory as well.
#
# Return true if the file is secure or missing, false otherwise.
# Note the extra parameter $exec which is set by exec_secure() only.
sub file_secure {
	local($file, $type, $exec) = @_;
	return 1 unless -e $file;	# Missing file considered secure

	# If we're trying to execute a symbolic link, try to resolve it recursively
	# Otherwise, symlinks are not considered secure by file_secure().
	if (-l $file) {				# File is a symbolic link
		if ($exec) {
			local($target);
			$target = &symfile_secure($file, $type);
			return 0 unless defined $target;
			&add_log("NOTICE running $type $file actually runs $target")
				if $loglvl > 6;
			$file = $target;
		} else {
			&add_log("WARNING sensitive $type file $file is a symbolic link")
				if $loglvl > 5;
			return 0;				# Unsecure file
		}
	}

	local($ST_MODE) = 2 + $[;	# Field st_mode from inode structure
	unless ($exec || -O _) {	# Reuse stat info from -e
		&add_log("WARNING you do not own $type file $file") if $loglvl > 5;
		return 0;		# Unsecure file
	}
	local($st_mode) = (stat(_))[$ST_MODE];
	if ($st_mode & $S_IWOTH) {
		&add_log("WARNING $type file $file is world writable!") if $loglvl > 5;
		return 0;		# Unsecure file
	}

	# If file is excutable and seg[ug]id, make sure it's not publicly writable.
	# If writable at all, only the owner should have the rights. That's for
	# systems which do no reset the set[ug]id bit on write to the file.
	if (-x _) {
		if (($st_mode & $S_ISUID) && ($st_mode & ($S_IWGRP|$S_IWOTH))) {
			&add_log("WARNING setuid $type file $file is writable!")
				if $loglvl > 5;
			return 0;
		}
		if (($st_mode & $S_ISGID) && ($st_mode & ($S_IWGRP|$S_IWOTH))) {
			&add_log("WARNING setgid $type file $file is writable!")
				if $loglvl > 5;
			return 0;
		}
	}

	return 1 unless $cf'secure =~ /on/i || $< == 0;

	# Extra checks for secure mode (or if root user). We make sure the
	# file is not writable by group and then we conduct the same secure tests
	# on the directory itself
	if (($st_mode & $S_IWGRP) && $cf'groupsafe !~ /^off/i) {
		&add_log("WARNING $type file $file is group writable!") if $loglvl > 5;
		return 0;		# Unsecure file
	}
	local($dir);		# directory where file is located
	$dir = '.' unless ($dir) = ($file =~ m|(.*)/.*|);
	unless ($exec || -O $dir) {
		&add_log("WARNING you do not own directory of $type file $file")
			if $loglvl > 5;
		return 0;		# Unsecure directory, therefore unsecure file
	}
	$st_mode = (stat(_))[$ST_MODE];
	return 0 unless &check_st_mode($dir, 1);

	# If linkdirs is OFF, we do not check further when faced with a symbolic
	# link to a directory.
	if (-l $dir && $cf'linkdirs !~ /^off/i && !&symdir_secure($dir, $type)) {
		&add_log("WARNING directory of $type file $file is an unsecure symlink")
			if $loglvl > 5;
		return 0;		# Unsecure directory
	}

	1;		# At last! File is secure...
}

# Is a symbolic link to a directory secure?
sub symdir_secure {
	local($dir, $type) = @_;
	if (&symdir_check($dir, 0)) {
		&add_log("symbolic directory $dir for $type file is secure")
			if $loglvl > 11;
		return 1;
	}
	0;	# Not secure
}

# Is a symbolic link to a file secure?
# Returns the final target if all links up to that file are secure, undef
# if one of the links is not secure enough.
sub symfile_secure {
	local($file, $type) = @_;
	local($target) = &symfile_check($file, 0);
	if (defined $target) {
		&add_log("symbolic file $file for $type file is secure")
			if $loglvl > 11;
	} else {
		&add_log("WARNING symbolic file $file for $type file is unsecure")
			if $loglvl > 5;
	}
	return $target;
}

# A symbolic directory (that is a symlink pointing to a directory) is secure
# if and only if:
#   - its target is a symlink that recursively proves to be secure.
#   - the target lies in a non world-writable directory
#   - the final directory at the end of the symlink chain is not world-writable
#   - less than $MAX_LINKS levels of indirection are needed to reach a real dir
# Unfortunately, we cannot check for group writability here for the parent
# target directory since the target might lie in a system directory which may
# have a legitimate need to be read/write for root and wheel, for instance.
# The routine returns 1 if the file is secure, 0 otherwise.
sub symdir_check {
	local($dir, $level) = @_;	# Directory, indirection level
	$MAX_LINKS = 100 unless defined $MAX_LINKS;	# May have been overridden
	if ($level++ > $MAX_LINKS) {
		&add_log("ERROR more than $MAX_LINKS levels of symlinks to reach $dir")
			if $loglvl;
		return 0
	}
	local($ndir) = readlink($dir);
	unless (defined $ndir) {
		&add_log("SYSERR readlink: $!") if $loglvl;
		return 0;
	}
	$dir =~ s|(.*)/.*|$1|;		# Suppress link component (tail)
	$dir = &cdir($ndir, $dir);	# Follow symlink to get its final path target
	local($still_link) = -l $dir;
	unless (-d $dir || $still_link) {
		&add_log("ERROR inconsistency: $dir is a plain file?") if $loglvl;
		return 0;		# Reached a plain file while following links to a dir!
	}
	unless (-d "$dir/..") {
		&add_log("ERROR inconsistency: $dir/.. is not a directory?") if $loglvl;
		return 0;		# Reached a file hooked nowhere in the file system!
	}
	# Check parent directory
	local($ST_MODE) = 2 + $[;	# Field st_mode from inode structure
	$st_mode = (stat(_))[$ST_MODE];
	return 0 unless &check_st_mode("$dir/..", 0);
	# Recurse if still a symbolic link
	if ($still_link) {
		return 0 unless &symdir_check($dir, $level);
	} else {
		$st_mode = (stat($dir))[$ST_MODE];
		return 0 unless &check_st_mode($dir, 1);
	}
	1;	# Ok, link is secure
}

# Same as symdir_check, but target is a file!
sub symfile_check {
	local($file, $level) = @_;	# File, indirection level
	return undef if $level++ > $MAX_LINKS;
	local($nfile) = readlink($file);
	unless (defined $nfile) {
		&add_log("SYSERR readlink: $!") if $loglvl;
		return undef;
	}
	local($dir) = $file;			# Where symlink was held
	$dir =~ s|(.*)/.*|$1|;			# Suppress link component (tail)
	$file = &cdir($nfile, $dir);	# Follow symlink to get its path
	local($still_link) = -l $file;
	unless (-f $file || $still_link) {
		&add_log("ERROR $file does not exist") if !-e _ && $loglvl;
		&add_log("ERROR $file is not a plain file") if -e _ && $loglvl;
		return undef;				# Reached something that is not a plain file
	}
	# Check parent directory
	($dir = $file) =~ s|(.*)/.*|$1|;
	local($ST_MODE) = 2 + $[;		# Field st_mode from inode structure
	$st_mode = (stat($dir))[$ST_MODE];
	return undef unless &check_st_mode($dir, 1);
	return $file unless $still_link;		# Ok, link is secure
	return &symfile_check($file, $level);	# Still a symbolic link
}

# Returns true if mode in $st_mode does not include world or group writable
# bits, false otherwise. This helps factorizing code used in both &file_secure
# and &symdir_check. Set $both to true if both world/group checks are desirable,
# false to get only world checks.
sub check_st_mode {
	local($dir, $both) = @_;
	if ($st_mode & $S_IWOTH) {
		&add_log("WARNING directory $dir of $type file is world writable!")
			if $loglvl > 5;
		return 0;		# Unsecure directory
	}
	return 1 unless $both;
	if (($st_mode & $S_IWGRP) && $cf'groupsafe !~ /^off/i) {
		&add_log("WARNING directory $dir of $type file is group writable!")
			if $loglvl > 5;
		return 0;		# Unsecure directory
	}
	1;
}

# Make sure the file we are about to execute is secure. If it is a script
# with the '#!' kernel hook, also check the interpreter! Returns true if the
# file can be executed "safely".
sub exec_secure {
	local($file) = @_;	# File to be executed

	unless (-x $file) {
		&add_log("ERROR lacking execute rights on $file") if $loglvl > 1;
		return 0;
	}

	return 1 if $cf'execskip =~ /^on/i;	# Assume safe to be exec'ed

	local($cf'secure) = $cf'execsafe;	# Use exec settings for file_secure()

	unless (&file_secure($file, 'program', 1)) {
		&add_log("ERROR cannot execute unsecure $file") if $loglvl > 1;
		return 0;
	}

	&add_log("can allow exec() of $file") if $loglvl > 17;

	return 1 unless -T $file;	# Safe as far as we can tell, unless script...

	local($head);				# Heading line
	local($interpretor);		# Interpretor running the script
	local($perl) = '';			# Empiric support for perl scripts
	local(*SCRIPT);

	unless (open(SCRIPT, $file)) {
		&add_log("SYSERR open: $!") if $loglvl > 1;
		&add_log("ERROR cannot check script $file") if $loglvl > 1;
		return 0;
	}

	$head = <SCRIPT>;

	# Allow empiric support for common perl scripts
	# This is not bullet-proof, but should guard against common errors.

	if ($head =~ /\bperl\b/) {
		$perl = <SCRIPT>;
		if ($perl =~ /\beval\b.*\bexec\s+(\S+)/) {
			$perl = $1;
		} else {
			$perl = '';			# False alarm, can't check further
		}
	}

	close SCRIPT;

	($interpretor) = $head =~ /^#!\s*(\S+)/;
	$interpretor = '/bin/sh' unless $interpretor;
	unless (-x $interpretor) {
		&add_log("ERROR lacking execute rights on $interpretor") if $loglvl > 1;
		return 0;
	}

	unless (&file_secure($interpretor, 'interpretor', 1)) {
		&add_log("ERROR cannot run unsecure interpretor $interpretor")
			if $loglvl > 1;
		&add_log("ERROR cannot allow execution of script $file") if $loglvl > 1;
		return 0;
	}

	&add_log("can allow $interpretor to run $file") if $loglvl > 17;

	return 1 unless $perl;		# Okay, can run the script

	$perl = &locate_program($perl) unless $perl =~ m|/|;
	unless (-x $perl) {
		&add_log("ERROR lacking execute rights on $perl") if $loglvl > 1;
		return 0;
	}

	unless (&file_secure($perl, 'perl', 1)) {
		&add_log("ERROR cannot run unsecure perl $perl")
			if $loglvl > 1;
		&add_log("ERROR cannot allow execution of perl script $file")
			if $loglvl > 1;
		return 0;
	}

	&add_log("can allow $perl to run $file") if $loglvl > 17;

	return 1;					# Okay, perl can run it
}

# Apply directory changes into current path and return new directory
sub cdir {
	local($dir, $cur) = @_;			# New relative path, current directory
	return $dir if $dir =~ m|^/|;	# Already an absolute path
	chop($cur = `pwd`) unless defined $cur;
	local(@cur) = split(/\//, $cur);
	local(@dir) = split(/\//, $dir);
	local($path);
	foreach $item (@dir) {
		next if $item eq '.';	# Stay in same dir
		if ($item eq '..') {	# Move up
			pop(@cur);
		} else {
			push(@cur, $item);	# Move down
		}
	}
	local($path) = '/' . join('/', @cur);
	$path =~ tr|/||s;			# Successive '/' are useless
	$path;
}

package addr;

#
# Address stuff, mainly for mailing list maintainance (package command)
#

# Is an address valid?
# Addresses containing either '|' or '/' in them are considered hostile, since
# sendmail for instance would attempt to deliver to a program or to a file...
# Also, the address must not contain any space or control characters.
# Since the address might also be given verbatim on a shell command line,
# it must not contain any "funny" shell meta-characters.
sub valid {
	local($_) = @_;
	return 0 if $_ eq '';		# Empty address
	return 0 if tr/\0-\31//;	# Control character found
	return 0 if /\s/;			# No space in address
	return 0 if m![\$^&*()[{}`\\|;><?]!;
	1;							# Address is ok
}

# Simplify address for comparaison purposes
sub simplify {
	local($_) = @_;

	return &simplify($_) if s/^@[\w-.]+://;			# @b.c:x -> x and retry
	return "$2\@$1.uucp" if /^([\w-]+)!(\w+)$/;		# b!u -> u@b.uucp
	return "$2\@$1" if /^([\w-.]+)!(\w+)$/;			# b.c!u -> u@b.c
	return $_ if /^[\w.-]+@[\w-.]+$/;				# u@b.c
	return &simplify("$2!$3")
		if /([^%@]+)!([\w-.]+)!(\w+)$/;				# ...!b!u -> b!u
	return "$1\@$2"
		if /^([\w.-]+)%([\w-.]+)@[\w-.]+/;			# u%b.c@d.e -> u@b.c
	return &simplify($1) if s/(.*)@[\w-.]+$//;		# x@b.c -> x and retry
	return &simplify("$1\@$2")
		if /^([\w-.%!]+)%([\w-.]+)$/;				# x%b -> x@b and retry

	return $_;		# Hmm... Better stop here, since we are clueless!!
}

# Does first address matches second address?
sub match {
	local($a1, $a2) = @_;		# Two plain e-mail addresses (no comments)
	$a1 =~ tr/A-Z/a-z/;			# Cannonicalize to lower case
	$a2 =~ tr/A-Z/a-z/;
	local($s1) = &simplify($a1);
	local($s2) = &simplify($a2);
	return 1 if $s1 eq $s2;
	# Face ram@lyon.eiffel.com versus ram@york.eiffel.com or ram@eiffel.com
	# We do not want a match in the first case, but it's ok for the other one.
	local($p1, $p2) = ($s1, $s2);
	$p1 =~ s/(\W)/\\$1/g;
	$p2 =~ s/(\W)/\\$1/g;
	$p1 =~ s/@/@[\\w-]+\\./;
	$p2 =~ s/@/@[\\w-]+\\./;
	$s1 =~ /^$p2$/ || $s2 =~ /^$p1$/;
}

# Are the two addresses close?
# They are if they match or if their login name is the same or they are
# within the same subdomain.domain.country or domain.country.
sub close {
	local($a1, $a2) = @_;		# Two plain e-mail addresses (no comments)
	return 1 if &match($a1, $a2);
	$a1 =~ tr/A-Z/a-z/;			# Cannonicalize to lower case
	$a2 =~ tr/A-Z/a-z/;
	$a1 = &simplify($a1);
	$a2 = &simplify($a2);
	local($l1, $l2);			# Login names
	local($d1, $d2);			# Domain names
	($l1) = $a1 =~ /^(.*)@/;
	($l2) = $a2 =~ /^(.*)@/;
	return 1 if $l1 ne '' && $l1 eq $l2;
	($d1) = $a1 =~ /\@([\w-]+\.[\w-]+\.[\w]+)$/;
	($d2) = $a2 =~ /\@([\w-]+\.[\w-]+\.[\w]+)$/;
	return 1 if $d1 ne '' && $d1 eq $d2;
	($d1) = $a1 =~ /\@([\w-]+\.[\w]+)$/;
	($d2) = $a2 =~ /\@([\w-]+\.[\w]+)$/;
	return 1 if $d1 ne '' && $d1 eq $d2;
	return 0;
}

package main;

#
# Find whether there is a .forward file and if there is, forge a new command
# mail and send it to the address(es) listed in this file, then exit.
# To forge the command message, we rely on the three global variables that
# should have been set from the environment passed by mailagent:
#
#   fullcmd: the shell command itself (without its leading @SH prefix)
#   pack   : the packing mode requested via @PACK (or default value)
#   path   : the path to be used to expand - addresses (@PATH or derived value)
#
# The recipient(s) will get a message which seems to come from us, but since
# there will be an explicit @PATH command and a leading message telling (in the
# body of the message itself) what has hapened, there should be no confusion
# possible. Automatic processing via mailagent of those forwarded requests is
# naturally possible transparently, without wondering about their origin.
#
# A note is sent to the originator of the command telling him his request has
# been forwarded, and to whom it was. That way, he may contact the other
# party if something wrong occurs.
sub check_forward {
	local(@addr) = &forward_list;
	return unless @addr;
	&add_log("NOTICE forwarding to @addr") if $loglvl > 6;
	local($es) = @addr == 1 ? '' : 'es';
	local($address) = join("\t\n", @addr);
	local(*MAIL);
	open(MAIL, "|$cf'sendmail $cf'mailopt $path $cf'email") || &nofork;
	print MAIL
"To: $path
Subject: Your command '$fullcmd' was forwarded
X-Mailer: mailagent [version $mversion PL$patchlevel]

You have sent $cf'email the following command:

	$fullcmd

It has been forwarded to the following address$es:

	$address

under the following (expanded) form:

	\@PATH $path
	\@PACK $pack
	\@SH $fullcmd

so that the remote end may interpret your command properly, if done
at all anyway.

-- $prog_name speaking for $cf'user
";
	close MAIL;
	if ($?) {
		&add_log("ERROR cannot notify $path about forwarding") if $loglvl;
	} else {
		&add_log("MSG forwarded to @addr") if $loglvl > 6;
	}
	local($addr) = join(", ", @addr);
	open(MAIL, "|$cf'sendmail $cf'mailopt @addr") || &nofork;
	print MAIL
"To: $addr
Subject: Command
X-Mailer: mailagent [version $mversion PL$patchlevel]

[Forwarded by $cf'email via mailagent $mversion PL$patchlevel]

\@PATH $path
\@PACK $pack
\@SH $fullcmd

-- $prog_name speaking for $cf'user
";
	close MAIL;
	if ($?) {
		&add_log("ERROR cannot forward command to @addr") if $loglvl;
	}

	# Final cleanup and exit
	&clean_tmp;
	exit 0;
}

# Returns the forwarding address list, or the empty list if none.
sub forward_list {
	return () unless -f '.forward';
	local(*FORWARD);
	unless (open(FORWARD, '.forward')) {
		&add_log("ERROR can't open .forward: $!") if $loglvl;
		return ();
	}
	local($_);
	local(@addr);
	push(@addr, split(/\s*,\s*/)) while chop($_ = <FORWARD>);
	close FORWARD;
	local(@valid);
	foreach $addr (@addr) {
		unless (&addr'valid($addr)) {
			&add_log("WARNING ignoring hostile forward address $addr")
				if $loglvl > 5;
			next;
		}
		push(@valid, $addr);
	}
	&add_log("WARNING empty forwarding address set!")
		if @valid == 0 && $loglvl > 5;
	return @valid;
}