File: err.c

package info (click to toggle)
daemon 0.6.4-1
  • links: PTS
  • area: main
  • in suites: buster, jessie, jessie-kfreebsd, squeeze, stretch, wheezy
  • size: 2,600 kB
  • ctags: 2,389
  • sloc: ansic: 28,824; sh: 3,036; perl: 594; makefile: 304
file content (1313 lines) | stat: -rw-r--r-- 31,523 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
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
/*
* libslack - http://libslack.org/
*
* Copyright (C) 1999-2010 raf <raf@raf.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
* or visit http://www.gnu.org/copyleft/gpl.html
*
* 20100612 raf <raf@raf.org>
*/

/*

=head1 NAME

I<libslack(err)> - message/error/debug/verbosity/alert messaging module

=head1 SYNOPSIS

    #include <slack/std.h>
    #include <slack/err.h>

    void msg(const char *format, ...);
    void vmsg(const char *format, va_list args);
    void verbose(size_t level, const char *format, ...);
    void vverbose(size_t level, const char *format, va_list args);
    void debugf(size_t level, const char *format, ...);
    void vdebugf(size_t level, const char *format, va_list args);
    int error(const char *format, ...);
    int verror(const char *format, va_list args);
    void fatal(const char *format, ...);
    void vfatal(const char *format, va_list args);
    void dump(const char *format, ...);
    void vdump(const char *format, va_list args);
    void alert(int priority, const char *format, ...);
    void valert(int priority, const char *format, va_list args);
    void debugsysf(size_t level, const char *format, ...);
    void vdebugsysf(size_t level, const char *format, va_list args);
    int errorsys(const char *format, ...);
    int verrorsys(const char *format, va_list args);
    void fatalsys(const char *format, ...);
    void vfatalsys(const char *format, va_list args);
    void dumpsys(const char *format, ...);
    void vdumpsys(const char *format, va_list args);
    void alertsys(int priority, const char *format, ...);
    void valertsys(int priority, const char *format, va_list args);
    int set_errno(int errnum);
    void *set_errnull(int errnum);
    void (*(set_errnullf)(int errnum))();

    #define debug(args)
    #define vdebug(args)
    #define debugsys(args)
    #define vdebugsys(args)
    #define check(test, mesg)

=head1 DESCRIPTION

This module works with the I<prog(3)> and I<msg(3)> modules to provide
functions for emitting various types of message with simple call syntax and
flexible behaviour. The message types catered for are: normal, verbose,
debug, error, fatal error, dump and alert messages. All messages are created
and sent with I<printf(3)>-like syntax. The destinations for these messages
are configurable by the client. Calling I<prog_init(3)> causes normal and
verbose messages to be sent to standard output; debug, error, fatal error,
dump and alert messages to be sent to standard error.

Calls to I<prog_set_out(3)>, I<prog_out_fd(3)>, I<prog_out_stdout(3)>,
I<prog_out_file(3)>, I<prog_out_syslog(3)> and I<prog_out_none(3)> cause
normal and verbose messages to be sent to the specified destination.

Calls to I<prog_set_err(3)>, I<prog_err_fd(3)>, I<prog_err_stderr(3)>,
I<prog_err_file(3)>, I<prog_err_syslog(3)> and I<prog_err_none(3)> cause
error, fatal error and dump messages to be sent to the specified
destination.

Calls to I<prog_set_dbg(3)>, I<prog_dbg_fd(3)>, I<prog_dbg_stdout(3)>,
I<prog_dbg_stderr(3)>, I<prog_dbg_file(3)>, I<prog_dbg_syslog(3)>,
I<prog_dbg_none(3)> cause debug messages to be sent to the specified
destination.

Calls to I<prog_set_alert(3)>, I<prog_alert_fd(3)>, I<prog_alert_stdout(3)>,
I<prog_alert_stderr(3)>, I<prog_alert_file(3)>, I<prog_alert_syslog(3)>,
I<prog_alert_none(3)> cause alert messages to be sent to the specified
destination.

Calls to the generic functions I<prog_set_out(3)>, I<prog_set_err(3)>,
I<prog_set_dbg(3)> and I<prog_set_alert(3)> cause their respective message
types to be sent to the specified destination or destinations (multiplexing
messages is only possible via these functions). See I<msg(3)> for more
details.

=over 4

=cut

*/

#ifndef _BSD_SOURCE
#define _BSD_SOURCE /* For snprintf() on OpenBSD-4.7 */
#endif

#include "config.h"
#include "std.h"

#include "msg.h"
#include "prog.h"
#include "err.h"

#ifndef HAVE_SNPRINTF
#include "snprintf.h"
#endif

#ifndef TEST

/*

=item C<void msg(const char *format, ...)>

Outputs a message to the program's normal message destination. C<format> is
a I<printf(3)>-like format string and processes any remaining arguments in
the same way as I<printf(3)>.

B<Warning: Do not under any circumstances ever pass a non-literal string as
the format argument unless you know exactly how many conversions will take
place. Being careless with this is a very good way to build potential
security holes into your programs. The same is true for all functions that
take a printf()-like format string as an argument.>

    msg(buf);       // EVIL
    msg("%s", buf); // GOOD

=cut

*/

void msg(const char *format, ...)
{
	va_list args;
	va_start(args, format);
	vmsg(format, args);
	va_end(args);
}

/*

=item C<void vmsg(const char *format, va_list args)>

Equivalent to I<msg(3)> with the variable argument list specified directly
as for I<vprintf(3)>.

=cut

*/

void vmsg(const char *format, va_list args)
{
	vmsg_out(prog_out(), format, args);
}

/*

=item C<void verbose(size_t level, const char *format, ...)>

Outputs a verbose message to the program's normal message destination if
C<level> is less than or equal to the program's current verbosity level. If
the program's name has been supplied using I<prog_set_name(3)>, the message
will be preceded by the name, a colon and a space. The message is also
preceded by as many spaces as the message level. This indents messages
according to their verbosity. C<format> is a I<printf(3)>-like format string
and processes any remaining arguments in the same way as I<printf(3)>. The
message is followed by a newline.

=cut

*/

void verbose(size_t level, const char *format, ...)
{
	if (prog_verbosity_level() >= level)
	{
		va_list args;
		va_start(args, format);
		vverbose(level, format, args);
		va_end(args);
	}
}

/*

=item C<void vverbose(size_t level, const char *format, va_list args)>

Equivalent to I<verbose(3)> with the variable argument list specified
directly as for I<vprintf(3)>.

=cut

*/

void vverbose(size_t level, const char *format, va_list args)
{
	if (prog_verbosity_level() >= level)
	{
		char mesg[MSG_SIZE];
		vsnprintf(mesg, MSG_SIZE, format, args);

		if (prog_name())
			msg_out(prog_out(), "%s: %*s%s\n", prog_name(), level, "", mesg);
		else
			msg_out(prog_out(), "%*s%s\n", level, "", mesg);
	}
}

/*

=item C<void debugf(size_t level, const char *format, ...)>

Outputs a debug message to the program's debug message destination if
C<level> satisfies the program's current debug level. The debug level is
broken into two components. The low byte specifies the level. The next three
bytes specify a section within which the level applies. Debug messages with
a section value whose bits overlap those of the program's current debug
section and with a level that is less than or equal to the program's current
debug level are emitted. As a convenience, if the program's current debug
section is zero, debug messages with a sufficiently small level are emitted
regardless of the message section. See I<prog_set_debug_level(3)> for
examples. If the program's name has been supplied using I<prog_set_name(3)>,
the message will be preceded by the name, a colon and a space. The message
is also preceded by as many spaces as the debug level. This indents debug
messages according to their debug level. C<format> is a I<printf(3)>-like
format string and processes any remaining arguments in the same way as
I<printf(3)>. The message is followed by a newline.

=cut

*/

static int debug_level_match(size_t level)
{
	size_t debug_level, debug_section, section;

	debug_level = prog_debug_level();
	debug_section = debug_level & 0xffffff00;
	debug_level &= 0x000000ff;
	section = level & 0xffffff00;
	level &= 0x000000ff;

	return (!debug_section || debug_section & section) && debug_level >= level;
}

void debugf(size_t level, const char *format, ...)
{
	if (debug_level_match(level))
	{
		va_list args;
		va_start(args, format);
		vdebugf(level, format, args);
		va_end(args);
	}
}

/*

=item C<void vdebugf(size_t level, const char *format, va_list args)>

Equivalent to I<debugf(3)> with the variable argument list specified
directly as for I<vprintf(3)>.

=cut

*/

void vdebugf(size_t level, const char *format, va_list args)
{
	if (debug_level_match(level))
	{
		char mesg[MSG_SIZE], prefix[32] = "";
		vsnprintf(mesg, MSG_SIZE, format, args);

		if (level & 0xffffff00)
			snprintf(prefix, 32, " [%d]", (int)((level & 0xffffff00) >> 8));

		if (prog_name())
			msg_out(prog_dbg(), "%s: debug:%s%*s%s\n", prog_name(), prefix, level & 0xff, "", mesg);
		else
			msg_out(prog_dbg(), "debug:%s%*s%s\n", prefix, level & 0xff, "", mesg);
	}
}

/*

=item C<int error(const char *format, ...)>

Outputs an error message to the program's error message destination. If the
program's name has been supplied using I<prog_set_name(3)>, the message will
be preceded by the name, a colon and a space. C<format> is a
I<printf(3)>-like format string and processes any remaining arguments in the
same way as I<printf(3)>. The message is followed by a newline. Returns -1.

=cut

*/

int error(const char *format, ...)
{
	va_list args;
	va_start(args, format);
	verror(format, args);
	va_end(args);

	return -1;
}

/*

=item C<int verror(const char *format, va_list args)>

Equivalent to I<error(3)> with the variable argument list specified directly
as for I<vprintf(3)>.

=cut

*/

int verror(const char *format, va_list args)
{
	char mesg[MSG_SIZE];
	vsnprintf(mesg, MSG_SIZE, format, args);

	if (prog_name())
		msg_out(prog_err(), "%s: %s\n", prog_name(), mesg);
	else
		msg_out(prog_err(), "%s\n", mesg);

	return -1;
}

/*

=item C<void fatal(const char *format, ...)>

Outputs an error message to the program's error message destination and then
calls I<exit(3)> with a return code of C<EXIT_FAILURE>. If the program's
name was supplied using I<prog_set_name(3)>, the message will be preceded
by the name, a colon and a space. This is followed by the string C<"fatal: ">.
C<format> is a I<printf(3)>-like format string and processes any remaining
arguments in the same way as I<printf(3)>. The message is followed by a
newline. B<Note:> Never use this in a library. Only an application can
decide which errors are fatal.

=cut

*/

void fatal(const char *format, ...)
{
	va_list args;
	va_start(args, format);
	vfatal(format, args);
	va_end(args); /* unreached */
}

/*

=item C<void vfatal(const char *format, va_list args)>

Equivalent to I<fatal(3)> with the variable argument list specified directly
as for I<vprintf(3)>.

=cut

*/

void vfatal(const char *format, va_list args)
{
	char mesg[MSG_SIZE];
	vsnprintf(mesg, MSG_SIZE, format, args);
	error("fatal: %s", mesg);
	exit(EXIT_FAILURE);
}

/*

=item C<void dump(const char *format, ...)>

Outputs an error message to the program's error message destination and then
calls I<abort(3)>. If the program's name was supplied using
I<prog_set_name(3)>, the message will be preceded by the name, a colon and
a space. This is followed by the string C<"dump: ">. C<format> is a
I<printf(3)>-like format string and processes any remaining arguments in the
same way as I<printf(3)>. The message is followed by a newline. B<Note:>
Never use this in a library. Only an application can decide which errors are
fatal.

=cut

*/

void dump(const char *format, ...)
{
	va_list args;
	va_start(args, format);
	vdump(format, args);
	va_end(args); /* unreached */
}

/*

=item C<void vdump(const char *format, va_list args)>

Equivalent to I<dump(3)> with the variable argument list specified directly
as for I<vprintf(3)>.

=cut

*/

void vdump(const char *format, va_list args)
{
	char mesg[MSG_SIZE];
	vsnprintf(mesg, MSG_SIZE, format, args);
	error("dump: %s", mesg);
	abort();
}

/*

=item C<void alert(int priority, const char *format, ...)>

Outputs an alert message of the given C<priority> to the program's alert
message destination. If the program's name has been supplied using
I<prog_set_name(3)>, the message will be preceded by the name, a colon and
a space. C<format> is a I<printf(3)>-like format string and processes any
remaining arguments in the same way as I<printf(3)>. The message is followed
by a newline. Note that this only works when the program's alert message
destination is a simple syslog destination. If the alert message destination
is anything else (including a multiplexing message destination containing
syslog destinations), C<priority> is ignored.

=cut

*/

void alert(int priority, const char *format, ...)
{
	va_list args;
	va_start(args, format);
	valert(priority, format, args);
	va_end(args);
}

/*

=item C<void valert(int priority, const char *format, va_list args)>

Equivalent to I<alert(3)> with the variable argument list specified directly
as for I<vprintf(3)>.

=cut

*/

void valert(int priority, const char *format, va_list args)
{
	Msg *alert;
	char mesg[MSG_SIZE];
	int err;

	vsnprintf(mesg, MSG_SIZE, format, args);

	alert = prog_alert();

	if ((err = msg_wrlock(alert)))
	{
		set_errno(err);
		return;
	}

	msg_syslog_set_priority_unlocked(alert, priority);

	if (prog_name())
		msg_out_unlocked(alert, "%s: %s\n", prog_name(), mesg);
	else
		msg_out_unlocked(alert, "%s\n", mesg);

	if ((err = msg_unlock(alert)))
		set_errno(err);
}

/*

=item C<void debugsysf(size_t level, const char *format, ...)>

Equivalent to I<debugf(3)> except that the message is followed by a colon, a
space, the string representation of C<errno> and a newline (rather than just
a newline).

=cut

*/

void debugsysf(size_t level, const char *format, ...)
{
	if (debug_level_match(level))
	{
		va_list args;
		va_start(args, format);
		vdebugsysf(level, format, args);
		va_end(args);
	}
}

/*

=item C<void vdebugsysf(size_t level, const char *format, va_list args)>

Equivalent to I<debugsysf(3)> with the variable argument list specified
directly as for I<vprintf(3)>.

=cut

*/

void vdebugsysf(size_t level, const char *format, va_list args)
{
	if (debug_level_match(level))
	{
		char mesg[MSG_SIZE];
		int errno_saved = errno;
		vsnprintf(mesg, MSG_SIZE, format, args);
		debugf(level, "%s: %s", mesg, strerror(errno_saved));
	}
}

/*

=item C<int errorsys(const char *format, ...)>

Equivalent to I<error(3)> except that the message is followed by a colon, a
space, the string representation of C<errno> and a newline (rather than just
a newline).

=cut

*/

int errorsys(const char *format, ...)
{
	va_list args;
	va_start(args, format);
	verrorsys(format, args);
	va_end(args);
	return -1;
}

/*

=item C<int verrorsys(const char *format, va_list args)>

Equivalent to I<errorsys(3)> with the variable argument list specified
directly as for I<vprintf(3)>.

=cut

*/

int verrorsys(const char *format, va_list args)
{
	char mesg[MSG_SIZE];
	int errno_saved = errno;
	vsnprintf(mesg, MSG_SIZE, format, args);
	return error("%s: %s", mesg, strerror(errno_saved));
}

/*

=item C<void fatalsys(const char *format, ...)>

Equivalent to I<fatal(3)> except that the message is followed by a colon, a
space, the string representation of C<errno> and a newline (rather than just
a newline).

=cut

*/

void fatalsys(const char *format, ...)
{
	va_list args;
	va_start(args, format);
	vfatalsys(format, args);
	va_end(args); /* unreached */
}

/*

=item C<void vfatalsys(const char *format, va_list args)>

Equivalent to I<fatalsys(3)> with the variable argument list specified
directly as for I<vprintf(3)>.

=cut

*/

void vfatalsys(const char *format, va_list args)
{
	char mesg[MSG_SIZE];
	int errno_saved = errno;
	vsnprintf(mesg, MSG_SIZE, format, args);
	fatal("%s: %s", mesg, strerror(errno_saved));
}

/*

=item C<void dumpsys(const char *format, ...)>

Equivalent to I<dump(3)> except that the message is followed by a colon, a
space, the string representation of C<errno> and a newline (rather than just
a newline).

=cut

*/

void dumpsys(const char *format, ...)
{
	va_list args;
	va_start(args, format);
	vdumpsys(format, args);
	va_end(args); /* unreached */
}

/*

=item C<void vdumpsys(const char *format, va_list args)>

Equivalent to I<dumpsys(3)> with the variable argument list specified
directly as for I<vprintf(3)>.

=cut

*/

void vdumpsys(const char *format, va_list args)
{
	char mesg[MSG_SIZE];
	int errno_saved = errno;
	vsnprintf(mesg, MSG_SIZE, format, args);
	dump("%s: %s", mesg, strerror(errno_saved));
}

/*

=item C<void alertsys(int priority, const char *format, ...)>

Equivalent to I<alert(3)> except that the message is followed by a colon, a
space, the string representation of C<errno> and a newline (rather than just
a newline).

=cut

*/

void alertsys(int priority, const char *format, ...)
{
	va_list args;
	va_start(args, format);
	valertsys(priority, format, args);
	va_end(args);
}

/*

=item C<void valertsys(int priority, const char *format, va_list args)>

Equivalent to I<alertsys(3)> with the variable argument list specified
directly as for I<vprintf(3)>.

=cut

*/

void valertsys(int priority, const char *format, va_list args)
{
	char mesg[MSG_SIZE];
	int errno_saved = errno;
	vsnprintf(mesg, MSG_SIZE, format, args);
	alert(priority, "%s: %s", mesg, strerror(errno_saved));
}

/*

=item C<int set_errno(int errnum)>

Sets C<errno> to C<errnum> and returns -1.

=cut

*/

int (set_errno)(int errnum)
{
	errno = errnum;
	return -1;
}

/*

=item C<void *set_errnull(int errnum)>

Sets C<errno> to C<errnum> and returns C<null>.

=cut

*/

void *(set_errnull)(int errnum)
{
	errno = errnum;
	return NULL;
}

/*

=item C<void (*set_errnullf(int errnum))()>

Sets C<errno> to C<errnum> and returns C<null> as a function pointer.
This is useful because ISO C doesn't like casting normal pointers
into function pointers.

=cut

*/

void (*(set_errnullf)(int errnum))()
{
	errno = errnum;
	return NULL;
}

/*

=item C< #define debug(args)>

Calls I<debugf(3)> unless C<NDEBUG> is defined. C<args> must be supplied
with extra parentheses. e.g.

    debug((1, "rc=%d", rc))

=item C< #define vdebug(args)>

Calls I<vdebugf(3)> unless C<NDEBUG> is defined. C<args> must be supplied
with extra parentheses. e.g.

    vdebug((1, format, args))

=item C< #define debugsys(args)>

Calls I<debugsysf(3)> unless C<NDEBUG> is defined. C<args> must be supplied
with extra parentheses. e.g.

    debugsys((1, "fd=%d", fd))

=item C< #define vdebugsys(args)>

Calls I<vdebugsysf(3)> unless C<NDEBUG> is defined. C<args> must be supplied
with extra parentheses. e.g.

    vdebugsys((1, format, args))

=item C< #define check(cond, mesg)>

Like I<assert(3)> but includes a string argument, C<mesg>, for including an
explanation of the condition tested and then calls I<dump(3)> to terminate
the program. This means the message will be sent to the right place(s)
rather than just to C<stderr>. B<Note:> Like I<assert(3)>, this function is
largely useless. It should never be left in production code (because it's
rude) so you need to write code to handle error conditions properly anyway.
You might as well not bother using I<assert(3)> or I<check(3)> in the first
place.

=back

=head1 MT-Level

MT-Safe

=head1 EXAMPLES

Send a range of messages to default locations:

    #include <slack/std.h>
    #include <slack/prog.h>
    #include <slack/err.h>

    int main(int ac, char **av)
    {
        prog_init();
        prog_set_debug_level(1);
        prog_set_verbosity_level(1);

        msg("This is a %s\n", "message");
        verbose(0, "This is a %s message (level %d)", "verbose", 0);
        verbose(1, "This is a %s message (level %d)", "verbose", 1);
        verbose(2, "This is a %s message (level %d)", "verbose", 2);
        debug((0, "This is a %s message (level %d)", "debug", 0))
        debug((1, "This is a %s message (level %d)", "debug", 1))
        debug((2, "This is a %s message (level %d)", "debug", 2))
        alert(LOG_ERR, "This is an %s message", "alert");
        error("This is an %s message", "error");
        fatal("This is a %s message", "fatal error");

        return EXIT_SUCCESS;
    }

=head1 SEE ALSO

I<libslack(3)>,
I<msg(3)>,
I<prog(3)>,
I<printf(3)>

=head1 AUTHOR

20100612 raf <raf@raf.org>

=cut

*/

#endif

#ifdef TEST

#include <fcntl.h>

#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>

int verify(int test, const char *name, const char *result)
{
	char buf[BUFSIZ];
	int fd;
	ssize_t bytes;

	if ((fd = open(name, O_RDONLY)) == -1)
	{
		printf("Test%d: failed to create err file: %s (%s)\n", test, name, strerror(errno));
		return 1;
	}

	memset(buf, 0, BUFSIZ);
	bytes = read(fd, buf, BUFSIZ);
	close(fd);
	unlink(name);

	if (bytes == -1)
	{
		printf("Test%d: failed to read err file: %s (%s)\n", test, name, strerror(errno));
		return 1;
	}

	if (!strstr(buf, result))
	{
		printf("Test%d: err file produced incorrect input:\nshould contain:\n%s\nwas:\n%s\n", test, result, buf);
		return 1;
	}

	return 0;
}

int verifysys(int test, const char *name, const char *result, int err)
{
	char buf[BUFSIZ];

	snprintf(buf, BUFSIZ, result, strerror(err));

	return verify(test, name, buf);
}

int main(int ac, char **av)
{
	const char * const out = "err.out";
	const char * const err = "err.err";
	const char * const dbg = "err.dbg";
	const char * const alertfile = "err.alert";
	const char * const core = "core";
	const char * const core2 = "err.core"; /* OpenBSD */
	char buf[BUFSIZ];
	int rci;
	void *rcp;
	void (*rcfp)();

	const char *results[12] =
	{
		"msg\n",
		"verbosemsg\n",
		"debug: debugmsg\n",
		"errormsg\n",
		"fatal: fatalmsg\n",
		"dump: dumpmsg\n",
		"debug: debugsysmsg: %s\n",
		"errorsysmsg: %s\n",
		"fatal: fatalsysmsg: %s\n",
		"dump: dumpsysmsg: %s\n",
		"debug: [1] lexer debugmsg\n"
		"debug: [2] parser debugmsg\n"
		"debug: [1] lexer debugmsg\n"
		"debug: [2] parser debugmsg\n"
		"debug: [4] interp debugmsg\n"
		"debug: global debugmsg\n",
		"alertmsg\n"
		"alertsysmsg: " /* followed by "Success" or "Error 0" */
	};

	pid_t pid;
	int errors = 0;

	if (ac == 2 && !strcmp(av[1], "help"))
	{
		printf("usage: %s\n", *av);
		return EXIT_SUCCESS;
	}

	printf("Testing: %s\n", "err");

	/* Test debug, verbose and error */

	prog_set_debug_level(1);
	prog_set_verbosity_level(1);

	prog_out_file(out);
	msg("msg\n");
	errors += verify(1, out, results[0]);

	prog_out_file(out);
	verbose(1, "verbosemsg");
	errors += verify(2, out, results[1]);

	prog_dbg_file(dbg);
	debugf(1, "debugmsg");
	errors += verify(3, dbg, results[2]);

	prog_err_file(err);
	error("errormsg");
	errors += verify(4, err, results[3]);

	/* Test fatal */

	switch (pid = fork())
	{
		case 0:
		{
			prog_err_file(err);
			fatal("fatalmsg");
		}

		case -1:
		{
			++errors;
			printf("Test5: failed to perform test - fork() failed (%s)\n", strerror(errno));
			break;
		}

		default:
		{
			int status;

			if (waitpid(pid, &status, 0) == -1)
			{
				++errors, printf("Test5: failed to wait for test - waitpid(%d) failed (%s)\n", (int)pid, strerror(errno));
				break;
			}

			if (!WIFEXITED(status) || WEXITSTATUS(status) != EXIT_FAILURE)
				++errors, printf("Test5: failed: %s %d\n",
					WIFSIGNALED(status) ? "received signal" : "exit code",
					WIFSIGNALED(status) ? WTERMSIG(status) : WEXITSTATUS(status));
		}
	}

	errors += verify(5, err, results[4]);

	/* Test dump */

	switch (pid = fork())
	{
		case 0:
		{
			prog_err_file(err);
			unlink(core);
			unlink(core2);
			dump("dumpmsg");
		}

		case -1:
		{
			++errors;
			printf("Test6: failed to perform test - fork() failed (%s)\n", strerror(errno));
			break;
		}

		default:
		{
			struct stat statbuf[1];
			int status;

			if (waitpid(pid, &status, 0) == -1)
			{
				++errors, printf("Test6: failed to wait for test - waitpid(%d) failed (%s)\n", (int)pid, strerror(errno));
				break;
			}

			if (!WIFSIGNALED(status) || WTERMSIG(status) != SIGABRT)
				++errors, printf("Test5: failed: %s %d\n",
					WIFSIGNALED(status) ? "received signal" : "exit code",
					WIFSIGNALED(status) ? WTERMSIG(status) : WEXITSTATUS(status));

			if (stat(core, statbuf) == -1 && errno == ENOENT &&
				stat(core2, statbuf) == -1 && errno == ENOENT)
				++errors, printf("Test6: failed: no core file produced (ulimit?)\n");
			else
			{
				unlink(core);
				unlink(core2);
			}
		}
	}

	errors += verify(6, err, results[5]);

	/* Test debugsys, errorsys */

	prog_dbg_file(dbg);
	set_errno(EPERM);
	debugsysf(1, "debugsysmsg");
	errors += verifysys(7, dbg, results[6], EPERM);

	prog_err_file(err);
	set_errno(ENOENT);
	errorsys("errorsysmsg");
	errors += verifysys(8, err, results[7], ENOENT);

	/* Test fatalsys */

	switch (pid = fork())
	{
		case 0:
		{
			prog_err_file(err);
			set_errno(EPERM);
			fatalsys("fatalsysmsg");
		}

		case -1:
		{
			++errors;
			printf("Test9: failed to perform test - fork() failed (%s)\n", strerror(errno));
			break;
		}

		default:
		{
			int status;

			if (waitpid(pid, &status, 0) == -1)
			{
				++errors;
				printf("Test9: failed to wait for test - waitpid(%d) failed (%s)\n", (int)pid, strerror(errno));
				break;
			}

			if (!WIFEXITED(status) || WEXITSTATUS(status) != EXIT_FAILURE)
				++errors, printf("Test5: failed: %s %d\n",
					WIFSIGNALED(status) ? "received signal" : "exit code",
					WIFSIGNALED(status) ? WTERMSIG(status) : WEXITSTATUS(status));
		}
	}

	errors += verifysys(9, err, results[8], EPERM);

	/* Test dumpsys */

	switch (pid = fork())
	{
		case 0:
		{
			prog_err_file(err);
			unlink(core);
			unlink(core2);
			set_errno(ENOENT);
			dumpsys("dumpsysmsg");
		}

		case -1:
		{
			++errors;
			printf("Test10: failed to perform test - fork() failed (%s)\n", strerror(errno));
			break;
		}

		default:
		{
			struct stat statbuf[1];
			int status;

			if (waitpid(pid, &status, 0) == -1)
			{
				++errors;
				printf("Test10: failed to wait for test - waitpid(%d) failed (%s)\n", (int)pid, strerror(errno));
				break;
			}

			if (!WIFSIGNALED(status) || WTERMSIG(status) != SIGABRT)
				++errors, printf("Test5: failed: %s %d\n",
					WIFSIGNALED(status) ? "received signal" : "exit code",
					WIFSIGNALED(status) ? WTERMSIG(status) : WEXITSTATUS(status));

			if (stat(core, statbuf) == -1 && errno == ENOENT &&
				stat(core2, statbuf) == -1 && errno == ENOENT)
				++errors, printf("Test10: failed: no core file produced (ulimit?)\n");
			else
			{
				unlink(core);
				unlink(core2);
			}
		}
	}

	errors += verifysys(10, err, results[9], ENOENT);

	/* Test check true */

	switch (pid = fork())
	{
		case 0:
		{
			int i = 1;
			prog_err_file(err);
			unlink(core);
			unlink(core2);
			set_errno(ENOENT);
			check(i == 1, "checkmsg");
			_exit(EXIT_SUCCESS);
		}

		case -1:
		{
			++errors;
			printf("Test11: failed to perform test - fork() failed (%s)\n", strerror(errno));
			break;
		}

		default:
		{
			int status;

			if (waitpid(pid, &status, 0) == -1)
			{
				++errors;
				printf("Test11: failed to wait for test - waitpid(%d) failed (%s)\n", (int)pid, strerror(errno));
				break;
			}

			if (!WIFEXITED(status) || WEXITSTATUS(status) != EXIT_SUCCESS)
				++errors, printf("Test5: failed: %s %d\n",
					WIFSIGNALED(status) ? "received signal" : "exit code",
					WIFSIGNALED(status) ? WTERMSIG(status) : WEXITSTATUS(status));
		}
	}

	/* Test check false */

	switch (pid = fork())
	{
		case 0:
		{
			int i = 1;
			prog_err_file(err);
			unlink(core);
			unlink(core2);
			set_errno(ENOENT);
			check(i == 0, "checkmsg");
			_exit(EXIT_SUCCESS);
		}

		case -1:
		{
			++errors;
			printf("Test12: failed to perform test - fork() failed (%s)\n", strerror(errno));
			break;
		}

		default:
		{
			struct stat statbuf[1];
			int status;

			if (waitpid(pid, &status, 0) == -1)
			{
				++errors;
				printf("Test12: failed to wait for test - waitpid(%d) failed (%s)\n", (int)pid, strerror(errno));
				break;
			}

			if (!WIFSIGNALED(status) || WTERMSIG(status) != SIGABRT)
				++errors, printf("Test5: failed: %s %d\n",
					WIFSIGNALED(status) ? "received signal" : "exit code",
					WIFSIGNALED(status) ? WTERMSIG(status) : WEXITSTATUS(status));

			if (stat(core, statbuf) == -1 && errno == ENOENT &&
				stat(core2, statbuf) == -1 && errno == ENOENT)
				++errors, printf("Test12: failed: no core file produced (ulimit?)\n");
			else
			{
				unlink(core);
				unlink(core2);
			}
		}
	}

	snprintf(buf, BUFSIZ, "dump: Internal Error: %s: %s [", "i == 0", "checkmsg");
	errors += verify(12, err, buf);

	/* Test debug sections */

#define LEXER_SECTION  (1 << 8)
#define PARSER_SECTION (2 << 8)
#define INTERP_SECTION (4 << 8)

    prog_set_debug_level(LEXER_SECTION | PARSER_SECTION | 1);
	prog_dbg_file(dbg);
	msg_set_timestamp_format("");

    debugf(LEXER_SECTION  | 1, "lexer debugmsg");  /* yes */
    debugf(LEXER_SECTION  | 4, "lexer debugmsg");  /* no (level too high) */
    debugf(PARSER_SECTION | 1, "parser debugmsg"); /* yes */
    debugf(INTERP_SECTION | 1, "interp debugmsg"); /* no (wrong section) */
    debugf(1, "global debugmsg");                  /* no (no section to match) */

    prog_set_debug_level(1);
    debugf(LEXER_SECTION  | 1, "lexer debugmsg");  /* yes */
    debugf(LEXER_SECTION  | 4, "lexer debugmsg");  /* no (level too high) */
    debugf(PARSER_SECTION | 1, "parser debugmsg"); /* yes */
    debugf(INTERP_SECTION | 1, "interp debugmsg"); /* yes */
    debugf(1, "global debugmsg");                  /* yes */
    debugf(4, "global debugmsg");                  /* no (level too high) */

	errors += verify(13, dbg, results[10]);

#undef LEXER_SECTION
#undef PARSER_SECTION
#undef INTERP_SECTION

	/* Test alert() and alertsys() */

	prog_alert_file(alertfile);
	alert(LOG_INFO, "alertmsg");
	errno = 0;
	alertsys(LOG_INFO, "alertsysmsg");
	errors += verify(14, alertfile, results[11]);

	prog_out_none();
	prog_err_none();
	prog_dbg_none();
	prog_alert_none();

	/* Test set_errno() and set_errnull() and set_errnullf() */

	errno = 0;
	if ((rci = set_errno(EINVAL)) != -1)
		++errors, printf("Test15: set_errno(EINVAL) failed (returned %d, not %d)\n", rci, -1);
	else if (errno != EINVAL)
		++errors, printf("Test15: set_errno(EINVAL) failed (errno = %s, not %s)\n", strerror(errno), strerror(EINVAL));

	errno = 0;
	if ((rcp = set_errnull(EINVAL)) != NULL)
		++errors, printf("Test16: set_errnull(EINVAL) failed (returned %p, not %p)\n", rcp, (void *)NULL);
	else if (errno != EINVAL)
		++errors, printf("Test16: set_errnull(EINVAL) failed (errno = %s, not %s)\n", strerror(errno), strerror(EINVAL));

	errno = 0;
	if ((rcfp = set_errnullf(EINVAL)) != NULL)
		/* ++errors, printf("Test17: set_errnullf(EINVAL) failed (returned %p, not %p)\n", rcfp, (void *)NULL); */
		++errors, printf("Test17: set_errnullf(EINVAL) failed (returned something other than null)\n");
	else if (errno != EINVAL)
		++errors, printf("Test17: set_errnullf(EINVAL) failed (errno = %s, not %s)\n", strerror(errno), strerror(EINVAL));

	if (errors)
		printf("%d/17 tests failed\n", errors);
	else
		printf("All tests passed\n");

	return (errors == 0) ? EXIT_SUCCESS : EXIT_FAILURE;
}

#endif

/* vi:set ts=4 sw=4: */