|
root / base / usr / src / cmd / fm / notify / smtp-notify
smtp-notify Plain Text 1284 lines 36.5 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
#
# 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 (c) 2010, Oracle and/or its affiliates. All rights reserved.
#

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

include ../Makefile.subdirs
#
# 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 (c) 2010, Oracle and/or its affiliates. All rights reserved.
#

.KEEP_STATE:
.SUFFIXES:

SRCS += smtp-notify.c
OBJS = $(SRCS:%.c=%.o)
LINTFILES = $(SRCS:%.c=%.ln)

PROG = smtp-notify
HELPER = process_msg_template.sh
ROOTLIBFM = $(ROOT)/usr/lib/fm
ROOTLIBNOTIFY = $(ROOT)/usr/lib/fm/notify
ROOTPROG = $(ROOTLIBNOTIFY)/$(PROG)
ROOTHELPER = $(ROOTLIBNOTIFY)/$(HELPER)

ROOTMANIFESTDIR = $(ROOTSVCSYSTEM)/fm
ROOTMANIFEST = $(ROOTMANIFESTDIR)/$(PROG).xml
ROOTNOTIFYPARAMS = $(ROOTMANIFESTDIR)/notify-params.xml
$(ROOTMANIFEST) : FILEMODE = 0444
$(ROOTNOTIFYPARAMS) : FILEMODE = 0444

$(NOT_RELEASE_BUILD)CPPFLAGS += -DDEBUG
CPPFLAGS += -I. -I../common -I../../../../../lib/fm/libfmnotify/common
CSTD	= $(CSTD_GNU99)
CFLAGS += $(CTF_FLAGS) $(CCVERBOSE)
CFLAGS64 += $(CTF_FLAGS_64) $(CCVERBOSE)
LDLIBS += -L$(ROOT)/usr/lib/fm -lnvpair -lfmevent -lfmd_msg -lfmnotify \
-lumem
LDFLAGS += -R/usr/lib/fm
# Hammerhead: GNU ld needs rpath-link for transitive deps (libtopo, libdiagcode)
LDFLAGS += -Wl,-rpath-link,$(ROOT)/usr/lib/fm
LINTFLAGS += -mnu

CERRWARN += -Wno-parentheses

.NOTPARALLEL:
.PARALLEL: $(OBJS) $(LINTFILES)

all: $(PROG) $(HELPER)

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

$(HELPER): ../common/$(HELPER)
	$(CP) ../common/$(HELPER) .

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

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

clean:
	$(RM) $(OBJS) $(HELPER) $(LINTFILES)

clobber: clean
	$(RM) $(PROG)

%.ln: ../common/%.c
	$(LINT.c) -c $<

%.ln: %.c
	$(LINT.c) -c $<

lint: $(LINTFILES)
	$(LINT) $(LINTFLAGS) $(LINTFILES)

$(ROOTLIBNOTIFY):
	$(INS.dir)

$(ROOTLIBNOTIFY)/%: %
	$(INS.file)

$(ROOTMANIFESTDIR):
	$(INS.dir)

$(ROOTMANIFESTDIR)/%.xml: ../common/%.xml
	$(INS.file)

$(ROOTMANIFESTDIR)/notify-params.xml: ../../notify-params.xml
	$(INS.file)

install_h:

install: all $(ROOTLIBNOTIFY) $(ROOTPROG) $(ROOTHELPER) $(ROOTMANIFESTDIR) \
$(ROOTMANIFEST) $(ROOTNOTIFYPARAMS)
#
# 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
#

# Hammerhead: Include Makefile.cmd first to load Makefile.master
# (defines COMPILE.c, COMPILE64.c needed by Makefile.com's pattern rules)
include $(SRC)/cmd/Makefile.cmd
include ../Makefile.com
include $(SRC)/cmd/Makefile.cmd.64

install: all $(ROOTPROG64)
#!/bin/sh

#
# 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 (c) 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# This is a simple helper script for smtp-notify which looks for certain
# expansion macros, which we've committed and converts them to valid
# libfmd_msg macros which directly reference event payload members.
#
# This allows us to change event payload names or alter the libfmd_msg
# expansion macro syntax without breaking user-supplied message body
# templates.
#
# We use all-caps for the committed macro names to avoid colliding
# with an actual event payload member name.
#
# Usage: process_msg_template.sh <infile> <outfile> <code> <severity>
#

#
# Verify template exists, is readable and is an ascii text file
#
if [ ! -e $1 ] || [ ! -r $1 ]; then
	exit 1
fi

/usr/has/bin/file $1 | grep "ascii text" > /dev/null
if [ $? != 0 ]; then
	exit 1
fi

tmpfile1=$2;
tmpfile2=`/usr/bin/mktemp -p /var/tmp`

cat $1 | sed s/\%\<CODE\>/$3/g > $tmpfile1
cat $tmpfile1 | sed s/\%\<UUID\>/\%\<uuid\>/g > $tmpfile2
cat $tmpfile2 | sed s/\%\<CLASS\>/\%\<class\>/g > $tmpfile1
cat $tmpfile1 | sed s/\%\<SEVERITY\>/$4/g > $tmpfile2
cat $tmpfile2 | sed s/\%\<FMRI\>/svc\:\\/\%\<attr.svc.svc-name\>\:\%\<attr.svc.svc-instance\>/g > $tmpfile1
cat $tmpfile1 | sed s/\%\<FROM-STATE\>/\%\<attr.from-state\>/g > $tmpfile2
cat $tmpfile2 | sed s/\%\<TO-STATE\>/\%\<attr.to-state\>/g > $tmpfile1
cat $tmpfile1 | sed s/\%\<HOSTNAME\>/\%h/g > $tmpfile2
cat $tmpfile2 | sed s/\%\<URL\>/\%s/g > $tmpfile1
rm -f $tmpfile2
exit 0
/*
 * 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 (c) 2010, Oracle and/or its affiliates. All rights reserved.
 */

/*
 * Copyright (c) 2018, Joyent, Inc.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <alloca.h>
#include <errno.h>
#include <fcntl.h>
#include <libscf.h>
#include <priv_utils.h>
#include <netdb.h>
#include <signal.h>
#include <strings.h>
#include <time.h>
#include <unistd.h>
#include <zone.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fm/fmd_msg.h>
#include <fm/libfmevent.h>
#include "libfmnotify.h"

#define	SENDMAIL	"/usr/sbin/sendmail"
#define	SVCNAME		"system/fm/smtp-notify"

#define	XHDR_HOSTNAME		"X-FMEV-HOSTNAME"
#define	XHDR_CLASS		"X-FMEV-CLASS"
#define	XHDR_UUID		"X-FMEV-UUID"
#define	XHDR_MSGID		"X-FMEV-CODE"
#define	XHDR_SEVERITY		"X-FMEV-SEVERITY"
#define	XHDR_FMRI		"X-FMEV-FMRI"
#define	XHDR_FROM_STATE		"X-FMEV-FROM-STATE"
#define	XHDR_TO_STATE		"X-FMEV-TO-STATE"

/*
 * Debug messages can be enabled by setting the debug property to true
 *
 * # svccfg -s svc:/system/fm/smtp-notify setprop config/debug=true
 *
 * Debug messages will be spooled to the service log at:
 * <root>/var/svc/log/system-fm-smtp-notify:default.log
 */
#define	PP_SCRIPT "usr/lib/fm/notify/process_msg_template.sh"

typedef struct email_pref
{
	int ep_num_recips;
	char **ep_recips;
	char *ep_reply_to;
	char *ep_template_path;
	char *ep_template;
} email_pref_t;

static nd_hdl_t *nhdl;
static char hostname[MAXHOSTNAMELEN + 1];
static const char optstr[] = "dfR:";
static const char DEF_SUBJ_TEMPLATE[] = "smtp-notify-subject-template";
static const char SMF_SUBJ_TEMPLATE[] = "smtp-notify-smf-subject-template";
static const char FM_SUBJ_TEMPLATE[] = "smtp-notify-fm-subject-template";
static const char IREPORT_MSG_TEMPLATE[] = "ireport-msg-template";
static const char SMF_MSG_TEMPLATE[] = "ireport.os.smf-msg-template";

static int
usage(const char *pname)
{
	(void) fprintf(stderr, "Usage: %s [-df] [-R <altroot>]\n", pname);

	(void) fprintf(stderr,
	    "\t-d  enable debug mode\n"
	    "\t-f  stay in foreground\n"
	    "\t-R  specify alternate root\n");

	return (1);
}

/*
 * This function simply reads the file specified by "template" into a buffer
 * and returns a pointer to that buffer (or NULL on failure).  The caller is
 * responsible for free'ing the returned buffer.
 */
static char *
read_template(const char *template)
{
	int fd;
	struct stat statb;
	char *buf;

	if (stat(template, &statb) != 0) {
		nd_error(nhdl, "Failed to stat %s (%s)", template,
		    strerror(errno));
		return (NULL);
	}
	if ((fd = open(template, O_RDONLY)) < 0) {
		nd_error(nhdl, "Failed to open %s (%s)", template,
		    strerror(errno));
		return (NULL);
	}
	if ((buf = malloc(statb.st_size + 1)) == NULL) {
		nd_error(nhdl, "Failed to allocate %d bytes", statb.st_size);
		(void) close(fd);
		return (NULL);
	}
	if (read(fd, buf, statb.st_size) < 0) {
		nd_error(nhdl, "Failed to read in template (%s)",
		    strerror(errno));
		free(buf);
		(void) close(fd);
		return (NULL);
	}
	buf[statb.st_size] = '\0';
	(void) close(fd);
	return (buf);
}

/*
 * This function runs a user-supplied message body template through a script
 * which replaces the "committed" expansion macros with actual libfmd_msg
 * expansion macros.
 */
static int
process_template(nd_ev_info_t *ev_info, email_pref_t *eprefs)
{
	char pp_script[PATH_MAX], tmpfile[PATH_MAX], pp_cli[PATH_MAX];
	int ret = -1;

	(void) snprintf(pp_script, sizeof (pp_script), "%s%s",
	    nhdl->nh_rootdir, PP_SCRIPT);
	(void) snprintf(tmpfile, sizeof (tmpfile), "%s%s",
	    nhdl->nh_rootdir, tmpnam(NULL));

	/*
	 * If it's an SMF event, then the diagcode and severity won't be part
	 * of the event payload and so libfmd_msg won't be able to expand them.
	 * Therefore we pass the code and severity into the script and let the
	 * script do the expansion.
	 */
	/* LINTED: E_SEC_SPRINTF_UNBOUNDED_COPY */
	(void) sprintf(pp_cli, "%s %s %s %s %s", pp_script,
	    eprefs->ep_template_path, tmpfile, ev_info->ei_diagcode,
	    ev_info->ei_severity);

	nd_debug(nhdl, "Executing %s", pp_cli);
	if (system(pp_cli) != -1)
		if ((eprefs->ep_template = read_template(tmpfile)) != NULL)
			ret = 0;

	(void) unlink(tmpfile);
	return (ret);
}

/*
 * If someone does an "svcadm refresh" on us, then this function gets called,
 * which rereads our service configuration.
 */
static void
get_svc_config()
{
	int s = 0;
	uint8_t val;

	s = nd_get_boolean_prop(nhdl, SVCNAME, "config", "debug", &val);
	nhdl->nh_debug = val;

	s += nd_get_astring_prop(nhdl, SVCNAME, "config", "rootdir",
	    &(nhdl->nh_rootdir));

	if (s != 0)
		nd_error(nhdl, "Failed to read retrieve service "
		    "properties\n");
}

static void
nd_sighandler(int sig)
{
	if (sig == SIGHUP)
		get_svc_config();
	else
		nd_cleanup(nhdl);
}

/*
 * This function constructs all the email headers and puts them into the
 * "headers" buffer handle.  The caller is responsible for free'ing this
 * buffer.
 */
static int
build_headers(nd_hdl_t *nhdl, nd_ev_info_t *ev_info, email_pref_t *eprefs,
    char **headers)
{
	const char *subj_key;
	char *subj_fmt, *subj = NULL;
	size_t len;
	boolean_t is_smf_event = B_FALSE, is_fm_event = B_FALSE;

	/*
	 * Fetch and format the email subject.
	 */
	if (strncmp(ev_info->ei_class, "list.", 5) == 0) {
		is_fm_event = B_TRUE;
		subj_key = FM_SUBJ_TEMPLATE;
	} else if (strncmp(ev_info->ei_class, "ireport.os.smf", 14) == 0) {
		is_smf_event = B_TRUE;
		subj_key = SMF_SUBJ_TEMPLATE;
	} else {
		subj_key = DEF_SUBJ_TEMPLATE;
	}

	if ((subj_fmt = fmd_msg_gettext_key(nhdl->nh_msghdl, NULL,
	    FMNOTIFY_MSG_DOMAIN, subj_key)) == NULL) {
		nd_error(nhdl, "Failed to contruct subject format");
		return (-1); /* libfmd_msg error */
	}

	if (is_fm_event) {
		/* LINTED: E_SEC_PRINTF_VAR_FMT */
		len = snprintf(NULL, 0, subj_fmt, hostname,
		    ev_info->ei_diagcode);
		subj = alloca(len + 1);
		/* LINTED: E_SEC_PRINTF_VAR_FMT */
		(void) snprintf(subj, len + 1, subj_fmt, hostname,
		    ev_info->ei_diagcode);
	} else if (is_smf_event) {
		/* LINTED: E_SEC_PRINTF_VAR_FMT */
		len = snprintf(NULL, 0, subj_fmt, hostname, ev_info->ei_fmri,
		    ev_info->ei_from_state, ev_info->ei_to_state);
		subj = alloca(len + 1);
		/* LINTED: E_SEC_PRINTF_VAR_FMT */
		(void) snprintf(subj, len + 1, subj_fmt, hostname,
		    ev_info->ei_fmri, ev_info->ei_from_state,
		    ev_info->ei_to_state);
	} else {
		/* LINTED: E_SEC_PRINTF_VAR_FMT */
		len = snprintf(NULL, 0, subj_fmt, hostname);
		subj = alloca(len + 1);
		/* LINTED: E_SEC_PRINTF_VAR_FMT */
		(void) snprintf(subj, len + 1, subj_fmt, hostname);
	}

	/*
	 * Here we add some X-headers to our mail message for use by mail
	 * filtering agents.  We add headers for the following bits of event
	 * data for all events
	 *
	 * hostname
	 * msg id (diagcode)
	 * event class
	 * event severity
	 * event uuid
	 *
	 * For SMF transition events, we'll have the following add'l X-headers
	 *
	 * from-state
	 * to-state
	 * service fmri
	 *
	 * We follow the X-headers with standard Reply-To and Subject headers.
	 */
	if (is_fm_event) {
		len = snprintf(NULL, 0, "%s: %s\n%s: %s\n%s: %s\n%s: %s\n"
		    "%s: %s\nReply-To: %s\nSubject: %s\n\n", XHDR_HOSTNAME,
		    hostname, XHDR_CLASS, ev_info->ei_class, XHDR_UUID,
		    ev_info->ei_uuid, XHDR_MSGID, ev_info->ei_diagcode,
		    XHDR_SEVERITY, ev_info->ei_severity, eprefs->ep_reply_to,
		    subj);

		*headers = calloc(len + 1, sizeof (char));

		(void) snprintf(*headers, len + 1, "%s: %s\n%s: %s\n%s: %s\n"
		    "%s: %s\n%s: %s\nReply-To: %s\nSubject: %s\n\n",
		    XHDR_HOSTNAME, hostname, XHDR_CLASS, ev_info->ei_class,
		    XHDR_UUID, ev_info->ei_uuid, XHDR_MSGID,
		    ev_info->ei_diagcode, XHDR_SEVERITY, ev_info->ei_severity,
		    eprefs->ep_reply_to, subj);
	} else if (is_smf_event) {
		len = snprintf(NULL, 0, "%s: %s\n%s: %s\n%s: %s\n%s: %s\n"
		    "%s: %s\n%s: %s\n%s: %s\nReply-To: %s\n"
		    "Subject: %s\n\n", XHDR_HOSTNAME, hostname, XHDR_CLASS,
		    ev_info->ei_class, XHDR_MSGID, ev_info->ei_diagcode,
		    XHDR_SEVERITY, ev_info->ei_severity, XHDR_FMRI,
		    ev_info->ei_fmri, XHDR_FROM_STATE, ev_info->ei_from_state,
		    XHDR_TO_STATE, ev_info->ei_to_state, eprefs->ep_reply_to,
		    subj);

		*headers = calloc(len + 1, sizeof (char));

		(void) snprintf(*headers, len + 1, "%s: %s\n%s: %s\n%s: %s\n"
		    "%s: %s\n%s: %s\n%s: %s\n%s: %s\nReply-To: %s\n"
		    "Subject: %s\n\n", XHDR_HOSTNAME, hostname, XHDR_CLASS,
		    ev_info->ei_class, XHDR_MSGID, ev_info->ei_diagcode,
		    XHDR_SEVERITY, ev_info->ei_severity, XHDR_FMRI,
		    ev_info->ei_fmri, XHDR_FROM_STATE, ev_info->ei_from_state,
		    XHDR_TO_STATE, ev_info->ei_to_state, eprefs->ep_reply_to,
		    subj);
	} else {
		len = snprintf(NULL, 0, "%s: %s\n%s: %s\n%s: %s\n%s: %s\n"
		    "Reply-To: %s\nSubject: %s\n\n", XHDR_HOSTNAME,
		    hostname, XHDR_CLASS, ev_info->ei_class, XHDR_MSGID,
		    ev_info->ei_diagcode, XHDR_SEVERITY, ev_info->ei_severity,
		    eprefs->ep_reply_to, subj);

		*headers = calloc(len + 1, sizeof (char));

		(void) snprintf(*headers, len + 1, "%s: %s\n%s: %s\n%s: %s\n"
		    "%s: %s\nReply-To: %s\nSubject: %s\n\n",
		    XHDR_HOSTNAME, hostname, XHDR_CLASS, ev_info->ei_class,
		    XHDR_MSGID, ev_info->ei_diagcode, XHDR_SEVERITY,
		    ev_info->ei_severity, eprefs->ep_reply_to, subj);
	}
	return (0);
}

static void
send_email(nd_hdl_t *nhdl, const char *headers, const char *body,
    const char *recip)
{
	FILE *mp;
	char sm_cli[PATH_MAX];

	/*
	 * Open a pipe to sendmail and pump out the email message
	 */
	(void) snprintf(sm_cli, PATH_MAX, "%s -t %s", SENDMAIL, recip);

	nd_debug(nhdl, "Sending email notification to %s", recip);
	if ((mp = popen(sm_cli, "w")) == NULL) {
		nd_error(nhdl, "Failed to open pipe to %s (%s)", SENDMAIL,
		    strerror(errno));
		return;
	}
	if (fprintf(mp, "%s", headers) < 0)
		nd_error(nhdl, "Failed to write to pipe (%s)", strerror(errno));

	if (fprintf(mp, "%s\n.\n", body) < 0)
		nd_error(nhdl, "Failed to write to pipe (%s)",
		    strerror(errno));

	(void) pclose(mp);
}

static void
send_email_template(nd_hdl_t *nhdl, nd_ev_info_t *ev_info, email_pref_t *eprefs)
{
	char *msg, *headers;

	if (build_headers(nhdl, ev_info, eprefs, &headers) != 0)
		return;

	/*
	 * If the user specified a message body template, then we pass it
	 * through a private interface in libfmd_msg, which will return a string
	 * with any expansion tokens decoded.
	 */
	if ((msg = fmd_msg_decode_tokens(ev_info->ei_payload,
	    eprefs->ep_template, ev_info->ei_url)) == NULL) {
		nd_error(nhdl, "Failed to parse msg template");
		free(headers);
		return;
	}
	for (int i = 0; i < eprefs->ep_num_recips; i++)
		send_email(nhdl, headers, msg, eprefs->ep_recips[i]);

	free(msg);
	free(headers);
}

static int
get_email_prefs(nd_hdl_t *nhdl, fmev_t ev, email_pref_t **eprefs)
{
	nvlist_t **p_nvl = NULL;
	email_pref_t *ep;
	uint_t npref, tn1 = 0, tn2 = 0;
	char **tmparr1, **tmparr2;
	int r, ret = -1;

	r = nd_get_notify_prefs(nhdl, "smtp", ev, &p_nvl, &npref);
	if (r == SCF_ERROR_NOT_FOUND) {
		/*
		 * No email notification preferences specified for this type of
		 * event, so we're done
		 */
		return (-1);
	} else if (r != 0) {
		nd_error(nhdl, "Failed to retrieve notification preferences "
		    "for this event");
		return (-1);
	}

	if ((ep = malloc(sizeof (email_pref_t))) == NULL) {
		nd_error(nhdl, "Failed to allocate space for email preferences "
		    "(%s)", strerror(errno));
		goto eprefs_done;
	}
	(void) memset(ep, 0, sizeof (email_pref_t));

	/*
	 * For SMF state transition events, pref_nvl may contain two sets of
	 * preferences, which will have to be merged.
	 *
	 * The "smtp" nvlist can contain up to four members:
	 *
	 * "active"	- boolean - used to toggle notfications
	 * "to"		- a string array of email recipients
	 * "reply-to"	- a string array containing the reply-to addresses
	 *		- this is optional and defaults to root@localhost
	 * "msg_template" - the pathname of a user-supplied message body
	 *		template
	 *
	 * In the case that we have two sets of preferences, we will merge them
	 * using the following rules:
	 *
	 * "active" will be set to true, if it is true in either set
	 *
	 * The "reply-to" and "to" lists will be merged, with duplicate email
	 * addresses removed.
	 */
	if (npref == 2) {
		boolean_t *act1, *act2;
		char **arr1, **arr2, **strarr, **reparr1, **reparr2;
		uint_t n1, n2, arrsz, repsz;

		r = nvlist_lookup_boolean_array(p_nvl[0], "active", &act1, &n1);
		r += nvlist_lookup_boolean_array(p_nvl[1], "active", &act2,
		    &n2);
		r += nvlist_lookup_string_array(p_nvl[0], "to", &arr1, &n1);
		r += nvlist_lookup_string_array(p_nvl[1], "to", &arr2, &n2);

		if (r != 0) {
			nd_error(nhdl, "Malformed email notification "
			    "preferences");
			nd_dump_nvlist(nhdl, p_nvl[0]);
			nd_dump_nvlist(nhdl, p_nvl[1]);
			goto eprefs_done;
		} else if (!act1[0] && !act2[0]) {
			nd_debug(nhdl, "Email notification is disabled");
			goto eprefs_done;
		}

		if (nd_split_list(nhdl, arr1[0], ",", &tmparr1, &tn1) != 0 ||
		    nd_split_list(nhdl, arr2[0], ",", &tmparr2, &tn2) != 0) {
			nd_error(nhdl, "Error parsing \"to\" lists");
			nd_dump_nvlist(nhdl, p_nvl[0]);
			nd_dump_nvlist(nhdl, p_nvl[1]);
			goto eprefs_done;
		}

		if ((ep->ep_num_recips = nd_merge_strarray(nhdl, tmparr1, tn1,
		    tmparr2, tn2, &ep->ep_recips)) < 0) {
			nd_error(nhdl, "Error merging email recipient lists");
			goto eprefs_done;
		}

		r = nvlist_lookup_string_array(p_nvl[0], "reply-to", &arr1,
		    &n1);
		r += nvlist_lookup_string_array(p_nvl[1], "reply-to", &arr2,
		    &n2);
		repsz = n1 = n2 = 0;
		if (!r &&
		    nd_split_list(nhdl, arr1[0], ",", &reparr1, &n1) != 0 ||
		    nd_split_list(nhdl, arr2[0], ",", &reparr2, &n2) != 0 ||
		    (repsz = nd_merge_strarray(nhdl, tmparr1, n1, tmparr2, n2,
		    &strarr)) != 0 ||
		    nd_join_strarray(nhdl, strarr, repsz, &ep->ep_reply_to)
		    != 0) {

			ep->ep_reply_to = strdup("root@localhost");
		}
		if (n1)
			nd_free_strarray(reparr1, n1);
		if (n2)
			nd_free_strarray(reparr2, n2);
		if (repsz > 0)
			nd_free_strarray(strarr, repsz);

		if (nvlist_lookup_string_array(p_nvl[0], "msg_template",
		    &strarr, &arrsz) == 0)
			ep->ep_template_path = strdup(strarr[0]);
	} else {
		char **strarr, **tmparr;
		uint_t arrsz;
		boolean_t *active;

		/*
		 * Both the "active" and "to" notification preferences are
		 * required, so if we have trouble looking either of these up
		 * we return an error.  We will also return an error if "active"
		 * is set to false.  Returning an error will cause us to not
		 * send a notification for this event.
		 */
		r = nvlist_lookup_boolean_array(p_nvl[0], "active", &active,
		    &arrsz);
		r += nvlist_lookup_string_array(p_nvl[0], "to", &strarr,
		    &arrsz);

		if (r != 0) {
			nd_error(nhdl, "Malformed email notification "
			    "preferences");
			nd_dump_nvlist(nhdl, p_nvl[0]);
			goto eprefs_done;
		} else if (!active[0]) {
			nd_debug(nhdl, "Email notification is disabled");
			goto eprefs_done;
		}

		if (nd_split_list(nhdl, strarr[0], ",", &tmparr, &arrsz)
		    != 0) {
			nd_error(nhdl, "Error parsing \"to\" list");
			goto eprefs_done;
		}
		ep->ep_num_recips = arrsz;
		ep->ep_recips = tmparr;

		if (nvlist_lookup_string_array(p_nvl[0], "msg_template",
		    &strarr, &arrsz) == 0)
			ep->ep_template_path = strdup(strarr[0]);

		if (nvlist_lookup_string_array(p_nvl[0], "reply-to", &strarr,
		    &arrsz) == 0)
			ep->ep_reply_to = strdup(strarr[0]);
		else
			ep->ep_reply_to = strdup("root@localhost");
	}
	ret = 0;
	*eprefs = ep;
eprefs_done:
	if (ret != 0) {
		if (ep->ep_recips)
			nd_free_strarray(ep->ep_recips, ep->ep_num_recips);
		if (ep->ep_reply_to)
			free(ep->ep_reply_to);
		free(ep);
	}
	if (tn1)
		nd_free_strarray(tmparr1, tn1);
	if (tn2)
		nd_free_strarray(tmparr2, tn2);
	nd_free_nvlarray(p_nvl, npref);

	return (ret);
}

/*ARGSUSED*/
static void
irpt_cbfunc(fmev_t ev, const char *class, nvlist_t *nvl, void *arg)
{
	char *body_fmt, *headers = NULL, *body = NULL, tstamp[32];
	struct tm ts;
	size_t len;
	nd_ev_info_t *ev_info = NULL;
	email_pref_t *eprefs;

	nd_debug(nhdl, "Received event of class %s", class);

	if (get_email_prefs(nhdl, ev, &eprefs) < 0)
		return;

	if (nd_get_event_info(nhdl, class, ev, &ev_info) != 0)
		goto irpt_done;

	/*
	 * If the user specified a template, then we pass it through a script,
	 * which post-processes any expansion macros.  Then we attempt to read
	 * it in and then send the message.  Otherwise we carry on with the rest
	 * of this function which will contruct the message body from one of the
	 * default templates.
	 */
	if (eprefs->ep_template != NULL)
		free(eprefs->ep_template);

	if (eprefs->ep_template_path != NULL &&
	    process_template(ev_info, eprefs) == 0) {
		send_email_template(nhdl, ev_info, eprefs);
		goto irpt_done;
	}

	/*
	 * Fetch and format the event timestamp
	 */
	if (fmev_localtime(ev, &ts) == NULL) {
		nd_error(nhdl, "Malformed event: failed to retrieve "
		    "timestamp");
		goto irpt_done;
	}
	(void) strftime(tstamp, sizeof (tstamp), NULL, &ts);

	/*
	 * We have two message body templates to choose from.  One for SMF
	 * service transition events and a generic one for any other
	 * uncommitted ireport.
	 */
	if (strncmp(class, "ireport.os.smf", 14) == 0) {
		/*
		 * For SMF state transition events we have a standard message
		 * template that we fill in based on the payload of the event.
		 */
		if ((body_fmt = fmd_msg_gettext_key(nhdl->nh_msghdl, NULL,
		    FMNOTIFY_MSG_DOMAIN, SMF_MSG_TEMPLATE)) == NULL) {
			nd_error(nhdl, "Failed to format message body");
			goto irpt_done;
		}

		/* LINTED: E_SEC_PRINTF_VAR_FMT */
		len = snprintf(NULL, 0, body_fmt, hostname, tstamp,
		    ev_info->ei_fmri, ev_info->ei_from_state,
		    ev_info->ei_to_state, ev_info->ei_descr,
		    ev_info->ei_reason);
		body = calloc(len, sizeof (char));
		/* LINTED: E_SEC_PRINTF_VAR_FMT */
		(void) snprintf(body, len, body_fmt, hostname, tstamp,
		    ev_info->ei_fmri, ev_info->ei_from_state,
		    ev_info->ei_to_state, ev_info->ei_descr,
		    ev_info->ei_reason);
	} else {
		if ((body_fmt = fmd_msg_gettext_key(nhdl->nh_msghdl, NULL,
		    FMNOTIFY_MSG_DOMAIN, IREPORT_MSG_TEMPLATE)) == NULL) {
			nd_error(nhdl, "Failed to format message body");
			goto irpt_done;
		}
		/* LINTED: E_SEC_PRINTF_VAR_FMT */
		len = snprintf(NULL, 0, body_fmt, hostname, tstamp, class);
		body = calloc(len, sizeof (char));
		/* LINTED: E_SEC_PRINTF_VAR_FMT */
		(void) snprintf(body, len, body_fmt, hostname, tstamp, class);
	}

	if (build_headers(nhdl, ev_info, eprefs, &headers) != 0)
		goto irpt_done;

	/*
	 * Everything is ready, so now we just iterate through the list of
	 * recipents, sending an email notification to each one.
	 */
	for (int i = 0; i < eprefs->ep_num_recips; i++)
		send_email(nhdl, headers, body, eprefs->ep_recips[i]);

irpt_done:
	free(headers);
	free(body);
	if (ev_info)
		nd_free_event_info(ev_info);
	if (eprefs->ep_recips)
		nd_free_strarray(eprefs->ep_recips, eprefs->ep_num_recips);
	if (eprefs->ep_reply_to)
		free(eprefs->ep_reply_to);
	free(eprefs);
}

/*
 * There is a lack of uniformity in how the various entries in our diagnosis
 * are terminated.  Some end with one newline, others with two.  This makes the
 * output look a bit ugly.  Therefore we postprocess the message before sending
 * it, removing consecutive occurences of newlines.
 */
static void
postprocess_msg(char *msg)
{
	int i = 0, j = 0;
	char *buf;

	if ((buf = malloc(strlen(msg) + 1)) == NULL)
		return;

	buf[j++] = msg[i++];
	for (i = 1; i < strlen(msg); i++) {
		if (!(msg[i] == '\n' && msg[i - 1] == '\n'))
			buf[j++] = msg[i];
	}
	buf[j] = '\0';
	(void) strncpy(msg, buf, j+1);
	free(buf);
}

/*ARGSUSED*/
static void
listev_cb(fmev_t ev, const char *class, nvlist_t *nvl, void *arg)
{
	char *body = NULL, *headers = NULL;
	nd_ev_info_t *ev_info = NULL;
	boolean_t domsg;
	email_pref_t *eprefs;

	nd_debug(nhdl, "Received event of class %s", class);

	if (get_email_prefs(nhdl, ev, &eprefs) < 0)
		return;

	if (nd_get_event_info(nhdl, class, ev, &ev_info) != 0)
		goto listcb_done;

	/*
	 * If the message payload member is set to 0, then it's an event we
	 * typically suppress messaging on, so we won't send an email for it.
	 */
	if (nvlist_lookup_boolean_value(ev_info->ei_payload, FM_SUSPECT_MESSAGE,
	    &domsg) == 0 && !domsg) {
		nd_debug(nhdl, "Messaging suppressed for this event");
		goto listcb_done;
	}

	/*
	 * If the user specified a template, then we pass it through a script,
	 * which post-processes any expansion macros.  Then we attempt to read
	 * it in and then send the message.  Otherwise we carry on with the rest
	 * of this function which will contruct the message body from one of the
	 * default templates.
	 */
	if (eprefs->ep_template != NULL)
		free(eprefs->ep_template);

	if (eprefs->ep_template_path != NULL &&
	    process_template(ev_info, eprefs) == 0) {
		send_email_template(nhdl, ev_info, eprefs);
		goto listcb_done;
	}

	/*
	 * Format the message body
	 *
	 * For FMA list.* events we use the same message that the
	 * syslog-msgs agent would emit as the message body
	 *
	 */
	if ((body = fmd_msg_gettext_nv(nhdl->nh_msghdl, NULL,
	    ev_info->ei_payload)) == NULL) {
		nd_error(nhdl, "Failed to format message body");
		nd_dump_nvlist(nhdl, ev_info->ei_payload);
		goto listcb_done;
	}
	postprocess_msg(body);

	if (build_headers(nhdl, ev_info, eprefs, &headers) != 0)
		goto listcb_done;

	/*
	 * Everything is ready, so now we just iterate through the list of
	 * recipents, sending an email notification to each one.
	 */
	for (int i = 0; i < eprefs->ep_num_recips; i++)
		send_email(nhdl, headers, body, eprefs->ep_recips[i]);

listcb_done:
	free(headers);
	free(body);
	if (ev_info)
		nd_free_event_info(ev_info);
	if (eprefs->ep_recips)
		nd_free_strarray(eprefs->ep_recips, eprefs->ep_num_recips);
	if (eprefs->ep_reply_to)
		free(eprefs->ep_reply_to);
	free(eprefs);
}

int
main(int argc, char *argv[])
{
	struct rlimit rlim;
	struct sigaction act;
	sigset_t set;
	int c;
	boolean_t run_fg = B_FALSE;

	if ((nhdl = malloc(sizeof (nd_hdl_t))) == NULL) {
		(void) fprintf(stderr, "Failed to allocate space for notifyd "
		    "handle (%s)", strerror(errno));
		return (1);
	}
	(void) memset(nhdl, 0, sizeof (nd_hdl_t));

	nhdl->nh_keep_running = B_TRUE;
	nhdl->nh_log_fd = stderr;
	nhdl->nh_pname = argv[0];

	get_svc_config();

	/*
	 * In the case where we get started outside of SMF, args passed on the
	 * command line override SMF property setting
	 */
	while (optind < argc) {
		while ((c = getopt(argc, argv, optstr)) != -1) {
			switch (c) {
			case 'd':
				nhdl->nh_debug = B_TRUE;
				break;
			case 'f':
				run_fg = B_TRUE;
				break;
			case 'R':
				nhdl->nh_rootdir = strdup(optarg);
				break;
			default:
				free(nhdl);
				return (usage(argv[0]));
			}
		}
	}

	/*
	 * Set up a signal handler for SIGTERM (and SIGINT if we'll
	 * be running in the foreground) to ensure sure we get a chance to exit
	 * in an orderly fashion.  We also catch SIGHUP, which will be sent to
	 * us by SMF if the service is refreshed.
	 */
	(void) sigfillset(&set);
	(void) sigfillset(&act.sa_mask);
	act.sa_handler = nd_sighandler;
	act.sa_flags = 0;

	(void) sigaction(SIGTERM, &act, NULL);
	(void) sigdelset(&set, SIGTERM);
	(void) sigaction(SIGHUP, &act, NULL);
	(void) sigdelset(&set, SIGHUP);

	if (run_fg) {
		(void) sigaction(SIGINT, &act, NULL);
		(void) sigdelset(&set, SIGINT);
	} else
		nd_daemonize(nhdl);

	rlim.rlim_cur = RLIM_INFINITY;
	rlim.rlim_max = RLIM_INFINITY;
	(void) setrlimit(RLIMIT_CORE, &rlim);

	/*
	 * We need to be root to initialize our libfmevent handle (because that
	 * involves reading/writing to /dev/sysevent), so we do this before
	 * calling __init_daemon_priv.
	 */
	nhdl->nh_evhdl = fmev_shdl_init(LIBFMEVENT_VERSION_2, NULL, NULL, NULL);
	if (nhdl->nh_evhdl == NULL) {
		(void) sleep(5);
		nd_abort(nhdl, "failed to initialize libfmevent: %s",
		    fmev_strerror(fmev_errno));
	}

	/*
	 * If we're in the global zone, reset all of our privilege sets to
	 * the minimum set of required privileges.  Since we've already
	 * initialized our libmevent handle, we no no longer need to run as
	 * root, so we change our uid/gid to noaccess (60002).
	 *
	 * __init_daemon_priv will also set the process core path for us
	 *
	 */
	if (getzoneid() == GLOBAL_ZONEID)
		if (__init_daemon_priv(
		    PU_RESETGROUPS | PU_LIMITPRIVS | PU_INHERITPRIVS,
		    60002, 60002, PRIV_PROC_SETID, NULL) != 0)
			nd_abort(nhdl, "additional privileges required to run");

	nhdl->nh_msghdl = fmd_msg_init(nhdl->nh_rootdir, FMD_MSG_VERSION);
	if (nhdl->nh_msghdl == NULL)
		nd_abort(nhdl, "failed to initialize libfmd_msg");

	(void) gethostname(hostname, MAXHOSTNAMELEN + 1);
	/*
	 * Set up our event subscriptions.  We subscribe to everything and then
	 * consult libscf when we receive an event to determine whether to send
	 * an email notification.
	 */
	nd_debug(nhdl, "Subscribing to ireport.* events");
	if (fmev_shdl_subscribe(nhdl->nh_evhdl, "ireport.*", irpt_cbfunc,
	    NULL) != FMEV_SUCCESS) {
		nd_abort(nhdl, "fmev_shdl_subscribe failed: %s",
		    fmev_strerror(fmev_errno));
	}

	nd_debug(nhdl, "Subscribing to list.* events");
	if (fmev_shdl_subscribe(nhdl->nh_evhdl, "list.*", listev_cb,
	    NULL) != FMEV_SUCCESS) {
		nd_abort(nhdl, "fmev_shdl_subscribe failed: %s",
		    fmev_strerror(fmev_errno));
	}

	/*
	 * We run until someone kills us
	 */
	while (nhdl->nh_keep_running)
		(void) sigsuspend(&set);

	free(nhdl->nh_rootdir);
	free(nhdl);

	return (0);
}
<?xml version="1.0"?>
<!DOCTYPE service_bundle SYSTEM "/usr/share/lib/xml/dtd/service_bundle.dtd.1">
<!--
 Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.

 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_bundle type='manifest' name='SUNWckr:fmd'>

<service
	name='system/fm/smtp-notify'
	type='service'
	version='1'>

	<create_default_instance enabled='true' />

	<!--
	 Just one instance of smtp-notify should be running in any OS instance.
	-->
	<single_instance />

	<!--
	    Add a dependency on SUNWfmd being installed
	-->
	<dependency
	    name='SUNWfmd'
	    grouping='require_all'
	    restart_on='none'
	    type='path'>
		<service_fmri value='file://localhost/usr/lib/fm/notify/smtp-notify' />
	</dependency>

	<dependency
	    name='startup_req'
	    grouping='require_all'
	    restart_on='none'
	    type='service'>
		<service_fmri value='svc:/milestone/multi-user:default' />
		<service_fmri value='svc:/system/fmd:default' />
	</dependency>

	<exec_method
	    type='method'
	    name='start'
	    exec='/usr/lib/fm/notify/smtp-notify'
	    timeout_seconds='0' />

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

        <exec_method
                type='method'
                name='refresh'
                exec=':kill -HUP'
                timeout_seconds='30'>
                <method_context working_directory='/'>
                        <method_credential user='root' group='root' />
                </method_context>
        </exec_method>

	<property_group name="general" type="framework">
		<propval name='action_authorization' type='astring'
                    value='solaris.smf.manage.smtp-notify' />
		<propval name='value_authorization' type='astring'
                    value='solaris.smf.value.smtp-notify' />
	</property_group>

	<property_group name="config" type="application">
		<propval name="debug" type="boolean" value="false"/>
		<propval name="rootdir" type="astring" value="/"/>
		<propval name='action_authorization' type='astring'
                    value='solaris.smf.manage.smtp-notify' />
		<propval name='value_authorization' type='astring'
                    value='solaris.smf.value.smtp-notify' />
	</property_group>

	<stability value='Evolving' />

	<template>
		<common_name>
			<loctext xml:lang='C'>
				Solaris Email Event Notification Agent
			</loctext>
		</common_name>
		<documentation>
			<manpage title='smtp-notify' section='8'
				manpath='/usr/share/man' />
		</documentation>
		<pg_pattern name='config' type='application' target='this'
		    required='false'>
			<prop_pattern name='debug' type='boolean'
			    required='false'>
				<description>
					<loctext xml:lang='C'>
When set to true, smtp-notify will spool debug messages to /var/fm/notify/smtp-notify.log
					</loctext>
				</description>
				<visibility value='readwrite'/>
				<cardinality min='1' max='1'/>
			</prop_pattern>
			<prop_pattern name='rootdir' type='astring'
			    required='false'>
				<description>
					<loctext xml:lang='C'>
The root directory that will be used for all pathnames evaluated by smtp-notify
					</loctext>
				</description>
				<visibility value='readwrite'/>
				<cardinality min='1' max='1'/>
			</prop_pattern>
		</pg_pattern>
	</template>
</service>

</service_bundle>