File: msg.c

package info (click to toggle)
daemon 0.8.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,072 kB
  • sloc: ansic: 30,432; sh: 4,310; perl: 592; makefile: 307
file content (1883 lines) | stat: -rw-r--r-- 43,598 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
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
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
/*
* libslack - https://libslack.org
*
* Copyright (C) 1999-2004, 2010, 2020-2023 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, see <https://www.gnu.org/licenses/>.
*
* 20230824 raf <raf@raf.org>
*/

/*

=head1 NAME

I<libslack(msg)> - message module

=head1 SYNOPSIS

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

    typedef struct Msg Msg;
    typedef void msg_out_t(void *data, const void *mesg, size_t mesglen);
    typedef int msg_filter_t(void **mesgp, const void *mesg, size_t mesglen);
    typedef void msg_release_t(void *data);

    Msg *msg_create(int type, msg_out_t *out, void *data, msg_release_t *destroy);
    Msg *msg_create_with_locker(Locker *locker, int type, msg_out_t *out, void *data, msg_release_t *destroy);
    int msg_rdlock(Msg *mesg);
    int msg_wrlock(Msg *mesg);
    int msg_unlock(Msg *mesg);
    void msg_release(Msg *mesg);
    void *msg_destroy(Msg **mesg);
    void msg_out(Msg *dst, const char *format, ...);
    void msg_out_unlocked(Msg *dst, const char *format, ...);
    void vmsg_out(Msg *dst, const char *format, va_list args);
    void vmsg_out_unlocked(Msg *dst, const char *format, va_list args);
    Msg *msg_create_fd(int fd);
    Msg *msg_create_fd_with_locker(Locker *locker, int fd);
    Msg *msg_create_stderr(void);
    Msg *msg_create_stderr_with_locker(Locker *locker);
    Msg *msg_create_stdout(void);
    Msg *msg_create_stdout_with_locker(Locker *locker);
    Msg *msg_create_file(const char *path);
    Msg *msg_create_file_with_locker(Locker *locker, const char *path);
    Msg *msg_create_syslog(const char *ident, int option, int facility, int priority);
    Msg *msg_create_syslog_with_locker(Locker *locker, const char *ident, int option, int facility, int priority);
    Msg *msg_syslog_set_facility(Msg *mesg, int facility);
    Msg *msg_syslog_set_facility_unlocked(Msg *mesg, int facility);
    Msg *msg_syslog_set_priority(Msg *mesg, int priority);
    Msg *msg_syslog_set_priority_unlocked(Msg *mesg, int priority);
    Msg *msg_create_plex(Msg *msg1, Msg *msg2);
    Msg *msg_create_plex_with_locker(Locker *locker, Msg *msg1, Msg *msg2);
    int msg_add_plex(Msg *mesg, Msg *item);
    int msg_add_plex_unlocked(Msg *mesg, Msg *item);
    Msg *msg_create_filter(msg_filter_t *filter, Msg *mesg);
    Msg *msg_create_filter_with_locker(Locker *locker, msg_filter_t *filter, Msg *mesg);
    const char *msg_set_timestamp_format(const char *format);
    int msg_set_timestamp_format_locker(Locker *locker);
    int syslog_lookup_facility(const char *facility);
    int syslog_lookup_priority(const char *priority);
    const char *syslog_facility_str(int spec);
    const char *syslog_priority_str(int spec);
    int syslog_parse(const char *spec, int *facility, int *priority);

=head1 DESCRIPTION

This module provides general messaging functions. Message channels can be
created that send messages to a file descriptor, a file, I<syslog> or a
client defined message handler or that multiplexes messages to any
combination of the above. Messages sent to files are timestamped using (by
default) the I<strftime(3)> format: C<"%Y%m%d %H:%M:%S">.

It also provides functions for parsing I<syslog> targets, converting between
I<syslog> facility names and codes, and converting between I<syslog>
priority names and codes.

=over 4

=cut

*/

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

#ifndef _DEFAULT_SOURCE
#define _DEFAULT_SOURCE /* New name for _BSD_SOURCE */
#endif

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

#include <syslog.h>
#include <fcntl.h>
#include <time.h>

#include <sys/stat.h>

#include "msg.h"
#include "mem.h"
#include "err.h"
#include "str.h"

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

typedef int MsgFDData;
typedef struct MsgFileData MsgFileData;
typedef struct MsgSyslogData MsgSyslogData;
typedef struct MsgFilterData MsgFilterData;
typedef struct MsgPlexData MsgPlexData;

#define MSG_FD 1
#define MSG_FILE 2
#define MSG_SYSLOG 3
#define MSG_PLEX 4
#define MSG_FILTER 5

struct Msg
{
	int type;               /* subtype */
	msg_out_t *out;         /* message handling function */
	void *data;             /* subtype specific data */
	msg_release_t *destroy; /* destructor function for data */
	Locker *locker;         /* locking strategy for this structure */
};

struct MsgFileData
{
	int fd;       /* file descriptor (-1 if open failed) */
};

struct MsgSyslogData
{
	int facility; /* syslog(3) priority */
	int priority; /* syslog(3) priority */
};

struct MsgPlexData
{
	size_t size;   /* elements allocated */
	size_t length; /* length of Msg list */
	Msg **list;    /* list of Msg objects */
};

struct MsgFilterData
{
	msg_filter_t *filter; /* filter function */
	Msg *mesg;            /* destination Msg */
};

typedef struct syslog_map_t syslog_map_t;

struct syslog_map_t
{
	char *name;
	int val;
};

/*
** The following masks might be wrong on some systems.
*/

#ifndef LOG_PRIMASK
#define LOG_PRIMASK 0x0007
#endif

#ifndef LOG_FACMASK
#define LOG_FACMASK 0x03f8
#endif

static const syslog_map_t syslog_facility_map[] =
{
	{ "kern",   LOG_KERN },
	{ "user",   LOG_USER },
	{ "mail",   LOG_MAIL },
	{ "daemon", LOG_DAEMON },
	{ "auth",   LOG_AUTH },
	{ "syslog", LOG_SYSLOG },
	{ "lpr",    LOG_LPR },
	{ "news",   LOG_NEWS },
	{ "uucp",   LOG_UUCP },
	{ "cron",   LOG_CRON },
	{ "local0", LOG_LOCAL0 },
	{ "local1", LOG_LOCAL1 },
	{ "local2", LOG_LOCAL2 },
	{ "local3", LOG_LOCAL3 },
	{ "local4", LOG_LOCAL4 },
	{ "local5", LOG_LOCAL5 },
	{ "local6", LOG_LOCAL6 },
	{ "local7", LOG_LOCAL7 },
	{ NULL,     -1 }
};

static const syslog_map_t syslog_priority_map[] =
{
	{ "emerg",   LOG_EMERG },
	{ "alert",   LOG_ALERT },
	{ "crit",    LOG_CRIT },
	{ "err",     LOG_ERR },
	{ "warning", LOG_WARNING },
#ifdef LOG_NOTICE
	{ "notice",  LOG_NOTICE },
#endif
	{ "info",    LOG_INFO },
	{ "debug",   LOG_DEBUG },
	{ NULL,      -1 }
};

#ifndef TEST

static const char *timestamp_format = "%Y%m%d %H:%M:%S ";
static Locker *timestamp_format_locker = NULL;

/*

=item C<Msg *msg_create(int type, msg_out_t *out, void *data, msg_release_t *destroy)>

Creates a I<Msg> object initialised with C<type>, C<out>, C<data> and
C<destroy>. Client-defined message handlers must specify a C<type> greater
than C<5>. It is the caller's responsibility to deallocate the new I<Msg>
with I<msg_release(3)> or I<msg_destroy>. It is strongly recommended to use
I<msg_destroy(3)>, because it also sets the pointer variable to C<null>. On
success, returns the new I<Msg> object. On error, returns C<null>.

=cut

*/

Msg *msg_create(int type, msg_out_t *out, void *data, msg_release_t *destroy)
{
	return msg_create_with_locker(NULL, type, out, data, destroy);
}

/*

=item C<Msg *msg_create_with_locker(Locker *locker, int type, msg_out_t *out, void *data, msg_release_t *destroy)>

Equivalent to I<msg_create(3)> except that multiple threads accessing the
new I<Msg> will be synchronised by C<locker>.

=cut

*/

Msg *msg_create_with_locker(Locker *locker, int type, msg_out_t *out, void *data, msg_release_t *destroy)
{
	Msg *mesg;

	if (!(mesg = mem_new(Msg)))
		return NULL;

	mesg->type = type;
	mesg->out = out;
	mesg->data = data;
	mesg->destroy = destroy;
	mesg->locker = locker;

	return mesg;
}

/*

=item C<int msg_rdlock(Msg *mesg)>

Claims a read lock on C<mesg> (if C<mesg> was created with a I<Locker>).
This is needed when multiple read-only I<msg(3)> module functions
need to be called atomically. It is the caller's responsibility to call
I<msg_unlock(3)> after the atomic operation. The only functions that may be
called on C<mesg> between calls to I<msg_rdlock(3)> and I<msg_unlock(3)> are
any read-only I<msg(3)> module functions whose name ends with
C<_unlocked>. On success, returns C<0>. On error, returns an error code.

=cut

*/

#define msg_rdlock(mesg) ((mesg) ? locker_rdlock((mesg)->locker) : EINVAL)
#define msg_wrlock(mesg) ((mesg) ? locker_wrlock((mesg)->locker) : EINVAL)
#define msg_unlock(mesg) ((mesg) ? locker_unlock((mesg)->locker) : EINVAL)

int (msg_rdlock)(Msg *mesg)
{
	return msg_rdlock(mesg);
}

/*

=item C<int msg_wrlock(Msg *mesg)>

Claims a write lock on C<mesg>.

Claims a write lock on C<mesg> (if C<mesg> was created with a I<Locker>).
This is needed when multiple read/write I<msg(3)> module functions
need to be called atomically. It is the caller's responsibility to call
I<msg_unlock(3)> after the atomic operation. The only functions that may be
called on C<mesg> between calls to I<msg_rdlock(3)> and I<msg_unlock(3)> are
any I<msg(3)> module functions whose name ends with C<_unlocked>. On
success, returns C<0>. On error, returns an error code.

=cut

*/

int (msg_wrlock)(Msg *mesg)
{
	return msg_wrlock(mesg);
}

/*

=item C<int msg_unlock(Msg *mesg)>

Unlocks a read or write lock on C<mesg> obtained with I<msg_rdlock(3)> or
I<msg_wrlock(3)> (if C<mesg> was created with a I<Locker>).  On success,
returns C<0>. On error, returns an error code.

=cut

*/

int (msg_unlock)(Msg *mesg)
{
	return msg_unlock(mesg);
}

/*

=item C<void msg_release(Msg *mesg)>

Releases (deallocates) C<mesg> and its internal data.

=cut

*/

void msg_release(Msg *mesg)
{
	if (!mesg)
		return;

	if (mesg->destroy)
		mesg->destroy(mesg->data);

	mem_release(mesg);
}

/*

=item C<void *msg_destroy(Msg **mesg)>

Destroys (deallocates and sets to C<null>) C<*mesg>. Returns C<null>.

=cut

*/

void *msg_destroy(Msg **mesg)
{
	if (mesg && *mesg)
	{
		msg_release(*mesg);
		*mesg = NULL;
	}

	return NULL;
}

/*

=item C<void msg_out(Msg *dst, const char *format, ...)>

Sends a message to C<dst>. C<format> is a I<printf(3)>-like format string.
Any remaining arguments are processed as in 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 vulnerabilities into your programs. The same is true for all
functions that take a printf()-like format string as an argument.>

    msg_out(dst, buf);       // EVIL
    msg_out(dst, "%s", buf); // GOOD

=cut

*/

void msg_out(Msg *dst, const char *format, ...)
{
	va_list args;
	va_start(args, format);
	vmsg_out(dst, format, args);
	va_end(args);
}

/*

=item C<void msg_out_unlocked(Msg *dst, const char *format, ...)>

Equivalent to I<msg_out(3)> except that C<dst> is not read-locked.

=cut

*/

void msg_out_unlocked(Msg *dst, const char *format, ...)
{
	va_list args;
	va_start(args, format);
	vmsg_out_unlocked(dst, format, args);
	va_end(args);
}

/*

=item C<void vmsg_out(Msg *dst, const char *format, va_list args)>

Sends a message to C<dst>. C<format> is a I<printf(3)>-like format string.
C<args> is processed as in I<vprintf(3)>.

=cut

*/

void vmsg_out(Msg *dst, const char *format, va_list args)
{
	int err;

	if (!dst)
		return;

	if ((err = msg_rdlock(dst)))
	{
		set_errno(err);
		return;
	}

	vmsg_out_unlocked(dst, format, args);

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

/*

=item C<void vmsg_out_unlocked(Msg *dst, const char *format, va_list args)>

Equivalent to I<vmsg_out(3)> except that C<dst> is not read-locked.

=cut

*/

void vmsg_out_unlocked(Msg *dst, const char *format, va_list args)
{
	if (!dst)
		return;

	if (dst->out)
	{
		char mesg[MSG_SIZE];
		vsnprintf(mesg, MSG_SIZE, format, args);
		dst->out(dst->data, mesg, strlen(mesg));
	}
}

/*

C<MsgFDData *msg_fddata_create(int fd)>

Creates and initialises the internal data needed by a I<Msg> object that
sends messages to file descriptor C<fd>. On success, returns the data. On
error, returns C<null>.

*/

static MsgFDData *msg_fddata_create(int fd)
{
	MsgFDData *data;

	if (!(data = mem_new(MsgFDData)))
		return NULL;

	*data = fd;

	return data;
}

/*

C<void msg_fddata_release(MsgFDData *data)>

Releases (deallocates) the internal data needed by a I<Msg> object that
sends messages to a file descriptor. The file descriptor is not closed.

*/

static void msg_fddata_release(MsgFDData *data)
{
	mem_release(data);
}

/*

C<void msg_out_fd(void *data, const void *mesg, size_t mesglen)>

Sends a message to a file descriptor. C<data> is a pointer to the file
descriptor. C<mesg> is the message. C<mesglen> is its length.

*/

static void msg_out_fd(void *data, const void *mesg, size_t mesglen)
{
	if (data && mesg)
		if (write(*(MsgFDData *)data, mesg, mesglen) == -1)
			/* Avoid gcc warning */;
}

/*

=item C<Msg *msg_create_fd(int fd)>

Creates a I<Msg> object that sends messages to file descriptor C<fd>. It is
the caller's responsibility to deallocate the new I<Msg> with
I<msg_release(3)> or I<msg_destroy(3)>. On success, returns the new I<Msg>
object. On error, returns C<null>.

=cut

*/

Msg *msg_create_fd(int fd)
{
	return msg_create_fd_with_locker(NULL, fd);
}

/*

=item C<Msg *msg_create_fd_with_locker(Locker *locker, int fd)>

Equivalent to I<msg_create_fd(3)> except that multiple threads accessing the
new I<Msg> will be synchronised by C<locker>.

=cut

*/

Msg *msg_create_fd_with_locker(Locker *locker, int fd)
{
	MsgFDData *data;
	Msg *mesg;

	if (!(data = msg_fddata_create(fd)))
		return NULL;

	if (!(mesg = msg_create_with_locker(locker, MSG_FD, msg_out_fd, data, (msg_release_t *)msg_fddata_release)))
	{
		msg_fddata_release(data);
		return NULL;
	}

	return mesg;
}

/*

=item C<Msg *msg_create_stderr(void)>

Creates a I<Msg> object that sends messages to standard error. It is the
caller's responsibility to deallocate the new I<Msg> with I<msg_release(3)>
or I<msg_destroy(3)>. It is strongly recommended to use I<msg_destroy(3)>,
because it also sets the pointer variable to C<null>. On success, returns
the new I<Msg> object. On error, returns C<null>.

=cut

*/

Msg *msg_create_stderr(void)
{
	return msg_create_fd_with_locker(NULL, STDERR_FILENO);
}

/*

=item C<Msg *msg_create_stderr_with_locker(Locker *locker)>

Equivalent to I<msg_create_stderr(3)> except that multiple threads accessing
the new I<Msg> will be synchronised by C<locker>.

=cut

*/

Msg *msg_create_stderr_with_locker(Locker *locker)
{
	return msg_create_fd_with_locker(locker, STDERR_FILENO);
}

/*

=item C<Msg *msg_create_stdout(void)>

Creates a I<Msg> object that sends messages to standard output. It is the
caller's responsibility to deallocate the new I<Msg> with I<msg_release(3)>
or I<msg_destroy(3)>. It is strongly recommended to use I<msg_destroy(3)>,
because it also sets the pointer variable to C<null>. On success, returns
the new I<Msg> object. On error, returns C<null>.

=cut

*/

Msg *msg_create_stdout(void)
{
	return msg_create_fd_with_locker(NULL, STDOUT_FILENO);
}

/*

=item C<Msg *msg_create_stdout_with_locker(Locker *locker)>

Equivalent to I<msg_create_stdout(3)> except that multiple threads accessing
the new I<Msg> will be synchronised by C<locker>.

=cut

*/

Msg *msg_create_stdout_with_locker(Locker *locker)
{
	return msg_create_fd_with_locker(locker, STDOUT_FILENO);
}

/*

C<int msg_filedata_init(MsgFileData *data, const char *path)>

Initialises the internal data needed by a I<Msg> object that sends messages
to the file specified by C<path>. This data consists of a copy of C<path>
and an open file descriptor to the file. The file descriptor is opened with
the C<O_WRONLY>, C<O_CREAT>, and C<O_APPEND> flags. On success, returns
C<0>. On error, returns C<-1> with C<errno> set appropriately.

*/

static int msg_filedata_init(MsgFileData *data, const char *path)
{
	mode_t mode;

	if (!data || !path)
		return set_errno(EINVAL);

	mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;

	if ((data->fd = open(path, O_WRONLY | O_CREAT | O_APPEND, mode)) == -1)
		return -1;

	return 0;
}

/*

C<MsgFileData *msg_filedata_create(const char *path)>

Creates the internal data needed by a I<Msg> object that sends messages to
the file specified by C<path>. On success, returns the data. On error,
returns C<null> with C<errno> set appropriately.

*/

static MsgFileData *msg_filedata_create(const char *path)
{
	MsgFileData *data;

	if (!(data = mem_new(MsgFileData)))
		return NULL;

	if (msg_filedata_init(data, path) == -1)
	{
		mem_release(data);
		return NULL;
	}

	return data;
}

/*

C<void msg_filedata_release(MsgFileData *data)>

Releases (deallocates) the internal data needed by a I<Msg> object that
sends messages to a file. The file descriptor is closed first.

*/

static void msg_filedata_release(MsgFileData *data)
{
	if (!data)
		return;

	if (data->fd != -1)
		close(data->fd);

	mem_release(data);
}

/*

C<void msg_out_file(void *data, const void *mesg, size_t mesglen)>

Sends a message to a file. C<data> contains the file descriptor. C<mesg> is
the message. C<mesglen> is its length. On error, sets C<errno>
appropriately.

*/

static void msg_out_file(void *data, const void *mesg, size_t mesglen)
{
	MsgFileData *dst = data;
	char buf[MSG_SIZE];
	size_t buflen;
	int err;

	time_t t = time(NULL);

	if ((err = locker_rdlock(timestamp_format_locker)))
	{
		set_errno(err);
		return;
	}

	strftime(buf, MSG_SIZE, timestamp_format, localtime(&t));

	if ((err = locker_unlock(timestamp_format_locker)))
	{
		set_errno(err);
		return;
	}

	buflen = strlen(buf);
	if (buflen + mesglen >= MSG_SIZE)
		mesglen -= MSG_SIZE - buflen;
	memmove(buf + buflen, mesg, mesglen);

	if (mesg && dst && dst->fd != -1)
		if (write(dst->fd, buf, buflen + mesglen) == -1)
			/* Avoid gcc warning */;
}

/*

=item C<Msg *msg_create_file(const char *path)>

Creates a I<Msg> object that sends messages to the file specified by
C<path>. It is the caller's responsibility to deallocate the new I<Msg> with
I<msg_release(3)> or I<msg_destroy(3)>. It is strongly recommended to use
I<msg_destroy(3)>, because it also sets the pointer variable to C<null>. On
success, returns the new I<Msg> object. On error, returns C<null> with
C<errno> set appropriately.

=cut

*/

Msg *msg_create_file(const char *path)
{
	return msg_create_file_with_locker(NULL, path);
}

/*

=item C<Msg *msg_create_file_with_locker(Locker *locker, const char *path)>

Equivalent to I<msg_create_file(3)> except that multiple threads accessing
the new I<Msg> will be synchronised by C<locker>.

=cut

*/

Msg *msg_create_file_with_locker(Locker *locker, const char *path)
{
	MsgFileData *data;
	Msg *mesg;

	if (!(data = msg_filedata_create(path)))
		return NULL;

	if (!(mesg = msg_create_with_locker(locker, MSG_FILE, msg_out_file, data, (msg_release_t *)msg_filedata_release)))
	{
		msg_filedata_release(data);
		return NULL;
	}

	return mesg;
}

/*

C<int msg_sysdata_init(MsgSyslogData *data, const char *ident, int option, int facility, int priority)>

Initialises the internal data needed by a I<Msg> object that sends messages
to I<syslog>. I<openlog(3)> is called with C<ident> and C<option>.
C<facility> and C<priority> are stored to be used when sending messages. On
success, returns C<0>. On error, returns C<-1> with C<errno> set
appropriately.

*/

static int msg_sysdata_init(MsgSyslogData *data, const char *ident, int option, int facility, int priority)
{
	if (!data || facility == -1)
		return set_errno(EINVAL);

	data->facility = facility & LOG_FACMASK;
	data->priority = priority & LOG_PRIMASK;

	openlog(ident, option, 0);

	return 0;
}

/*

C<MsgSyslogData *msg_sysdata_create(const char *ident, int option, int facility, int priority)>

Creates the internal data needed by a I<Msg> object that sends messages to
I<syslog>. C<ident>, C<option>, C<facility> and C<priority> are used to
initialise the connection to I<syslog>. On success, returns the data. On
error, returns C<null> with C<errno> set appropriately.

*/

static MsgSyslogData *msg_sysdata_create(const char *ident, int option, int facility, int priority)
{
	MsgSyslogData *data;

	if (!(data = mem_new(MsgSyslogData)))
		return NULL;

	if (msg_sysdata_init(data, ident, option, facility, priority) == -1)
	{
		mem_release(data);
		return NULL;
	}

	return data;
}

/*

C<void msg_sysdata_release(MsgSyslogData *data)>

Releases (deallocates) the internal data needed by a I<Msg> object that
sends messages to I<syslog>. Calls I<closelog(3)>.

*/

static void msg_sysdata_release(MsgSyslogData *data)
{
	if (!data)
		return;

	mem_release(data);
	closelog();
}

/*

C<void msg_out_syslog(void *data, const void *mesg, size_t mesglen)>

Sends a message to I<syslog>. C<data> is a pointer to a C<MsgSyslogData>
object that contains the facility and priority to use. C<mesg> is the
message. C<mesglen> is its length.

*/

static void msg_out_syslog(void *data, const void *mesg, size_t mesglen)
{
	MsgSyslogData *dst = data;

	if (mesg && dst && dst->facility != -1)
		syslog(dst->facility | dst->priority, "%*.*s", (int)mesglen, (int)mesglen, (char *)mesg);
}

/*

=item C<Msg *msg_create_syslog(const char *ident, int option, int facility, int priority)>

Creates a I<Msg> object that sends messages to I<syslog> initialised with
C<ident>, C<option>, C<facility> and C<priority>. It is the caller's
responsibility to deallocate the new I<Msg> with I<msg_release(3)> or
I<msg_destroy(3)>. It is strongly recommended to use I<msg_destroy(3)>,
because it also sets the pointer variable to C<null>. On success, returns
the new I<Msg> object. On error, returns C<null> with C<errno> set
appropriately.

=cut

*/

Msg *msg_create_syslog(const char *ident, int option, int facility, int priority)
{
	return msg_create_syslog_with_locker(NULL, ident, option, facility, priority);
}

/*

=item C<Msg *msg_create_syslog_with_locker(Locker *locker, const char *ident, int option, int facility, int priority)>

Equivalent to I<msg_create_syslog(3)> except that multiple threads accessing
the new I<Msg> will be synchronised by C<locker>.

=cut

*/

Msg *msg_create_syslog_with_locker(Locker *locker, const char *ident, int option, int facility, int priority)
{
	MsgSyslogData *data;
	Msg *mesg;

	if (!(data = msg_sysdata_create(ident, option, facility, priority)))
		return NULL;

	if (!(mesg = msg_create_with_locker(locker, MSG_SYSLOG, msg_out_syslog, data, (msg_release_t *)msg_sysdata_release)))
	{
		msg_sysdata_release(data);
		return NULL;
	}

	return mesg;
}

/*

=item C<Msg *msg_syslog_set_facility(Msg *mesg, int facility)>

Sets the facility field in C<mesg>'s data to C<facility>. On success,
returns C<mesg>. On error, returns C<null> with C<errno> set appropriately.

=cut

*/

Msg *msg_syslog_set_facility(Msg *mesg, int facility)
{
	Msg *ret;
	int err;

	if (!mesg)
		return set_errnull(EINVAL);

	if ((err = msg_wrlock(mesg)))
		return set_errnull(err);

	ret = msg_syslog_set_facility_unlocked(mesg, facility);

	if ((err = msg_unlock(mesg)))
		return set_errnull(err);

	return ret;
}

/*

=item C<Msg *msg_syslog_set_facility_unlocked(Msg *mesg, int facility)>

Equivalent to I<msg_syslog_set_facility(3)> except that C<mesg> is not
write-locked.

=cut

*/

Msg *msg_syslog_set_facility_unlocked(Msg *mesg, int facility)
{
	MsgSyslogData *data;

	if (!mesg || mesg->type != MSG_SYSLOG)
		return set_errnull(EINVAL);

	data = (MsgSyslogData *)mesg->data;
	data->facility = facility;

	return mesg;
}

/*

=item C<Msg *msg_syslog_set_priority(Msg *mesg, int priority)>

Sets the priority field in C<mesg>'s data to C<priority>. On success,
returns C<mesg>. On error, returns C<null> with C<errno> set appropriately.

=cut

*/

Msg *msg_syslog_set_priority(Msg *mesg, int priority)
{
	Msg *ret;
	int err;

	if (!mesg)
		return set_errnull(EINVAL);

	if ((err = msg_wrlock(mesg)))
		return set_errnull(err);

	ret = msg_syslog_set_priority_unlocked(mesg, priority);

	if ((err = msg_unlock(mesg)))
		return set_errnull(err);

	return ret;
}

/*

=item C<Msg *msg_syslog_set_priority_unlocked(Msg *mesg, int priority)>

Equivalent to I<msg_syslog_set_priority(3)> except that C<mesg> is not
write-locked.

=cut

*/

Msg *msg_syslog_set_priority_unlocked(Msg *mesg, int priority)
{
	MsgSyslogData *data;

	if (!mesg || mesg->type != MSG_SYSLOG)
		return set_errnull(EINVAL);

	data = (MsgSyslogData *)mesg->data;
	data->priority = priority;

	return mesg;
}

/*

C<int msg_plexdata_init(Msg *msg1, Msg *msg2)>

Initialises the internal data needed by a I<Msg> object that multiplexes
messages to several I<Msg> objects. On success, returns C<0>. On error,
returns C<-1> with C<errno> set appropriately.

*/

static int msg_plexdata_init(MsgPlexData *data, Msg *msg1, Msg *msg2)
{
	data->length = data->size = 2;

	if (!(data->list = mem_create(data->size, Msg *)))
		return -1;

	data->list[0] = msg1;
	data->list[1] = msg2;

	return 0;
}

/*

C<int msg_plexdata_add(MsgPlexData *data, Msg *mesg)>

Adds C<mesg> to a list of multiplexed I<Msg> objects. On success, returns
C<0>. On error, returns C<-1> with C<errno> set appropriately.

*/

static int msg_plexdata_add(MsgPlexData *data, Msg *mesg)
{
	if (data->length == data->size)
	{
		size_t new_size = data->size << 1;
		Msg **new_list = mem_resize(&data->list, new_size);
		if (!new_list)
			return -1;

		data->size = new_size;
		data->list = new_list;
	}

	data->list[data->length++] = mesg;

	return 0;
}

/*

C<MsgPlexData *msg_plexdata_create(Msg *msg1, Msg * msg2)>

Creates the internal data needed by a I<Msg> object that multiplexes
messages to several I<Msg> objects. Further I<Msg> objects can be added to
the list with I<msg_plexdata_add(3)>. On success, returns the data. On
error, returns C<null> with C<errno> set appropriately.

*/

static MsgPlexData *msg_plexdata_create(Msg *msg1, Msg *msg2)
{
	MsgPlexData *data;

	if (!(data = mem_new(MsgPlexData)))
		return NULL;

	if (msg_plexdata_init(data, msg1, msg2) == -1)
	{
		mem_release(data);
		return NULL;
	}

	return data;
}

/*

C<void msg_plexdata_release(MsgPlexData *data)>

Releases (deallocates) the internal data needed by a I<Msg> object that
multiplexes messages to several I<Msg> objects.

*/

static void msg_plexdata_release(MsgPlexData *data)
{
	size_t i;

	if (!data)
		return;

	for (i = 0; i < data->length; ++i)
		msg_destroy(data->list + i);

	mem_release(data->list);
	mem_release(data);
}

/*

C<void msg_out_plex(void *data, const void *mesg, size_t mesglen)>

Multiplexes a message to several I<Msg> objects. C<data> contains the list
of I<Msg> objects. C<mesg> is the message. C<mesglen> is its length.

*/

static void msg_out_plex(void *data, const void *mesg, size_t mesglen)
{
	MsgPlexData *dst = data;
	size_t i;

	if (mesg && dst)
	{
		for (i = 0; i < dst->length; ++i)
		{
			Msg *out = dst->list[i];
			if (out && out->out)
				out->out(out->data, mesg, mesglen);
		}
	}
}

/*

=item C<Msg *msg_create_plex(Msg *msg1, Msg *msg2)>

Creates a I<Msg> object that multiplexes messages to C<msg1> and C<msg2>.
Further I<Msg> objects may be added to its list using I<msg_add_plex(3)>. It
is the caller's responsibility to deallocate the new I<Msg> with
I<msg_release(3)> or I<msg_destroy(3)>. It is strongly recommended to use
I<msg_destroy(3)>, because it also sets the pointer variable to C<null>. On
success, returns the new I<Msg> object. On error, returns C<null> with
C<errno> set appropriately.

=cut

*/

Msg *msg_create_plex(Msg *msg1, Msg *msg2)
{
	return msg_create_plex_with_locker(NULL, msg1, msg2);
}

/*

=item C<Msg *msg_create_plex_with_locker(Locker *locker, Msg *msg1, Msg *msg2)>

Equivalent to I<msg_create_plex(3)> except that multiple threads accessing
the new I<Msg> will be synchronised by C<locker>.

=cut

*/

Msg *msg_create_plex_with_locker(Locker *locker, Msg *msg1, Msg *msg2)
{
	MsgPlexData *data;
	Msg *mesg;

	if (!(data = msg_plexdata_create(msg1, msg2)))
		return NULL;

	if (!(mesg = msg_create_with_locker(locker, MSG_PLEX, msg_out_plex, data, (msg_release_t *)msg_plexdata_release)))
	{
		msg_plexdata_release(data);
		return NULL;
	}

	return mesg;
}

/*

=item C<int msg_add_plex(Msg *mesg, Msg *item)>

Adds C<item> to the list of I<Msg> objects multiplexed by C<mesg>. On
success, returns C<0>. On error, returns C<-1> with C<errno> set
appropriately.

=cut

*/

int msg_add_plex(Msg *mesg, Msg *item)
{
	int ret;
	int err;

	if (!mesg)
		return set_errno(EINVAL);

	if ((err = msg_wrlock(mesg)))
		return set_errno(err);

	ret = msg_add_plex_unlocked(mesg, item);

	if ((err = msg_unlock(mesg)))
		return set_errno(err);

	return ret;
}

/*

=item C<int msg_add_plex_unlocked(Msg *mesg, Msg *item)>

Equivalent to I<msg_add_plex(3)> except that C<mesg> is not write-locked.

=cut

*/

int msg_add_plex_unlocked(Msg *mesg, Msg *item)
{
	if (!mesg || mesg->type != MSG_PLEX)
		return set_errno(EINVAL);

	return msg_plexdata_add((MsgPlexData *)mesg->data, item);
}

/*

C<MsgFilterData *msg_filterdata_create(msg_filter_t *filter, Msg *mesg)>

Creates the internal data needed by a I<Msg> object that sends filtered
messages to another I<Msg> object, I<mesg>. C<filter> and C<mesg> are used
to initialise a I<msg> object. On success, returns the data. On error,
returns C<null> with C<errno> set appropriately.

*/

static MsgFilterData *msg_filterdata_create(msg_filter_t *filter, Msg *mesg)
{
	MsgFilterData *data;

	if (!filter || !mesg)
		return set_errnull(EINVAL);

	if (!(data = mem_new(MsgFilterData)))
		return NULL;

	data->filter = filter;
	data->mesg = mesg;

	return data;
}

/*

C<void msg_filterdata_release(MsgFilterData *data)>

Releases (deallocates) the internal data needed by a I<Msg> object that
sends filtered messages to another I<Msg> object.

*/

static void msg_filterdata_release(MsgFilterData *data)
{
	if (!data)
		return;

	msg_release(data->mesg);
	mem_release(data);
}

/*

C<void msg_out_filter(void *data, const void *mesg, size_t mesglen)>

Filters and sends a message to another I<Msg> object. C<data> contains the
filter function and the destination I<Msg> object. C<mesg> is the unfiltered
message. C<mesglen> is its length.

*/

static void msg_out_filter(void *data, const void *mesg, size_t mesglen)
{
	MsgFilterData *filter_data = data;
	void *filtered_mesg;
	int filtered_mesglen;

	if (!filter_data || !mesg || !mesglen)
		return;

	if ((filtered_mesglen = filter_data->filter(&filtered_mesg, mesg, mesglen)) == -1)
		return;

	filter_data->mesg->out(filter_data->mesg->data, filtered_mesg, filtered_mesglen);
	mem_release(filtered_mesg);
}

/*

=item C<Msg *msg_create_filter(msg_filter_t *filter, Msg *mesg)>

Creates a I<Msg> object that sends messages to I<mesg> after filtering
messages through the I<filter> function which must dynamically create a
modified version of its input message which will be deallocated by its
caller. It is the caller's responsibility to deallocate the new I<Msg> with
I<msg_release(3)> or I<msg_destroy(3)>. It is strongly recommended to use
I<msg_destroy(3)>, because it also sets the pointer variable to C<null>. On
success, returns the new I<Msg> object. On error, returns C<null> with
C<errno> set appropriately.

=cut

*/

Msg *msg_create_filter(msg_filter_t *filter, Msg *mesg)
{
	return msg_create_filter_with_locker(NULL, filter, mesg);
}

/*

=item C<Msg *msg_create_filter_with_locker(Locker *locker, msg_filter_t *filter, Msg *mesg)>

Equivalent to I<msg_create_filter(3)> except that multiple threads accessing
the new I<Msg> will be synchronised by C<locker>.

=cut

*/

Msg *msg_create_filter_with_locker(Locker *locker, msg_filter_t *filter, Msg *mesg)
{
	MsgFilterData *data;
	Msg *newmesg;

	if (!(data = msg_filterdata_create(filter, mesg)))
		return NULL;

	if (!(newmesg = msg_create_with_locker(locker, MSG_FILTER, msg_out_filter, data, (msg_release_t *)msg_filterdata_release)))
	{
		msg_filterdata_release(data);
		return NULL;
	}

	return newmesg;
}

/*

=item C<const char *msg_set_timestamp_format(const char *format)>

Sets the I<strftime(3)> format string used when sending messages to a file.
By default, it is C<"%Y%m%d %H:%M:%S ">. On success, returns the previous
format string. On error, returns C<null> with C<errno> set appropriately.

=cut

*/

const char *msg_set_timestamp_format(const char *format)
{
	const char *save;
	int err;

	if (!format)
		return set_errnull(EINVAL);

	if ((err = locker_wrlock(timestamp_format_locker)))
		return set_errnull(err);

	save = timestamp_format;
	timestamp_format = format;

	if ((err = locker_unlock(timestamp_format_locker)))
		return set_errnull(err);

	return save;
}

/*

=item C<int msg_set_timestamp_format_locker(Locker *locker)>

Sets the locking strategy for changing the timestamp format used when
sending messages to a file. This is only needed if the timestamp format will
be modified in multiple threads. On success, returns C<0>. On error, returns
C<-1> with C<errno> set appropriately.

=cut

*/

int msg_set_timestamp_format_locker(Locker *locker)
{
	if (timestamp_format_locker)
		return set_errno(EINVAL);

	timestamp_format_locker = locker;

	return 0;
}

/*

C<int syslog_lookup(const syslog_map_t *map, const char *name)>

Looks for C<name> (a facility or priority name) in C<map>. If found, returns
its corresponding code. If not found, returns C<-1>.

*/

static int syslog_lookup(const syslog_map_t *map, const char *name)
{
	int i;

	for (i = 0; map[i].name; ++i)
		if (!strcmp(name, map[i].name))
			break;

	return map[i].val;
}

/*

C<const char *syslog_lookup_str(const syslog_map_t *map, int spec)>

Looks for C<spec> (a facility or priority code) in C<map>. If found, returns
its corresponding name. If not found, returns C<null>.

*/

static const char *syslog_lookup_str(const syslog_map_t *map, int spec, int mask)
{
	int i;

	for (i = 0; map[i].name; ++i)
		if ((spec & mask) == map[i].val)
			break;

	return map[i].name;
}

/*

=item C<int syslog_lookup_facility(const char *facility)>

Returns the code corresponding to C<facility>. If not found, returns C<-1>.

=cut

*/

int syslog_lookup_facility(const char *facility)
{
	return syslog_lookup(syslog_facility_map, facility);
}

/*

=item C<int syslog_lookup_priority(const char *priority)>

Returns the code corresponding to C<priority>. If not found, returns C<-1>.

=cut

*/

int syslog_lookup_priority(const char *priority)
{
	return syslog_lookup(syslog_priority_map, priority);
}

/*

=item C<const char *syslog_facility_str(int spec)>

Returns the name corresponding to the facility part of C<spec>. If not
found, returns C<null>.

=cut

*/

const char *syslog_facility_str(int spec)
{
	return syslog_lookup_str(syslog_facility_map, spec, LOG_FACMASK);
}

/*

=item C<const char *syslog_priority_str(int spec)>

Returns the name corresponding to the priority part of C<spec>. If not
found, returns C<null>.

=cut

*/

const char *syslog_priority_str(int spec)
{
	return syslog_lookup_str(syslog_priority_map, spec, LOG_PRIMASK);
}

/*

=item C<int syslog_parse(const char *spec, int *facility, int *priority)>

Parses C<spec> as a I<facility.priority> string. If C<facility> is
non-C<null>, the parsed facility is stored in the location pointed to by
C<facility>. If C<priority> is non-C<null> the parsed priority is stored in
the location pointed to by C<priority>. On success, returns C<0>. On error,
returns C<-1> with C<errno> set appropriately.

These are the supported syslog facility and priority names and their
corresponding symbolic constants:

    syslog facilities          syslog priorities
    ----------------------     -----------------------
    "kern"      LOG_KERN       "emerg"       LOG_EMERG
    "user"      LOG_USER       "alert"       LOG_ALERT
    "mail"      LOG_MAIL       "crit"        LOG_CRIT
    "daemon"    LOG_DAEMON     "err"         LOG_ERR
    "auth"      LOG_AUTH       "warning"     LOG_WARNING
    "syslog"    LOG_SYSLOG     "info"        LOG_INFO
    "lpr"       LOG_LPR        "debug"       LOG_DEBUG
    "news"      LOG_NEWS
    "uucp"      LOG_UUCP
    "cron"      LOG_CRON
    "local0"    LOG_LOCAL0
    "local1"    LOG_LOCAL1
    "local2"    LOG_LOCAL2
    "local3"    LOG_LOCAL3
    "local4"    LOG_LOCAL4
    "local5"    LOG_LOCAL5
    "local6"    LOG_LOCAL6
    "local7"    LOG_LOCAL7

=cut

*/

int syslog_parse(const char *spec, int *facility, int *priority)
{
	char fac[64], *pri;
	int f, p;

	if (!spec)
		return set_errno(EINVAL);

	strlcpy(fac, spec, 64);

	if (!(pri = strchr(fac, '.')))
		return set_errno(EINVAL);

	*pri++ = '\0';

	if ((f = syslog_lookup_facility(fac)) == -1)
		return set_errno(EINVAL);

	if ((p = syslog_lookup_priority(pri)) == -1)
		return set_errno(EINVAL);

	if (facility)
		*facility = f;

	if (priority)
		*priority = p;

	return 0;
}

/*

=back

=head1 ERRORS

On error, C<errno> is set by underlying functions or as follows:

=over 4

=item C<EINVAL>

An argument was C<null>, or could not be parsed.

=back

=head1 MT-Level

I<MT-Disciplined> - msg functions - See I<locker(3)> for details.

I<MT-Safe> - syslog functions

=head1 EXAMPLE

Parse syslog facility priority pair:

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

    int main(int ac, char **av)
    {
        int facility, priority;

        if (syslog_parse(av[1], &facility, &priority) != -1)
            syslog(facility | priority, "syslog(%s)", av[1]);

        return EXIT_SUCCESS;
    }

Multiplex a message to several locations:

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

    int main(int ac, char **av)
    {
        Msg *stdout_msg = msg_create_stdout();
        Msg *stderr_msg = msg_create_stderr();
        Msg *file_msg = msg_create_file("/tmp/junk");
        Msg *syslog_msg = msg_create_syslog("ident", 0, LOG_DAEMON, LOG_ERR);
        Msg *plex_msg = msg_create_plex(stdout_msg, stderr_msg);

        msg_add_plex(plex_msg, file_msg);
        msg_add_plex(plex_msg, syslog_msg);

        msg_out(plex_msg, "Multiplex message\n");
        unlink("/tmp/junk");

        return EXIT_SUCCESS;
    }

=head1 SEE ALSO

I<libslack(3)>,
I<err(3)>,
I<prog(3)>,
I<openlog(3)>,
I<syslog(3)>,
I<locker(3)>

=head1 AUTHOR

20230824 raf <raf@raf.org>

=cut

*/

#endif

#ifdef TEST

static int verify(int test, const char *name, const char *mesg)
{
	char buf[MSG_SIZE];
	int fd;
	ssize_t bytes;

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

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

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

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

	return 0;
}

static int prefix_filter(void **mesgp, const void *mesg, size_t mesglen)
{
	if (!mesgp || !mesg)
		return -1;

	return asprintf((char **)mesgp, "[%d] %.*s", 12345, (int)mesglen, (char *)mesg);
}

int main(int ac, char **av)
{
	const char *msg_file_name = "./msg.file";
	const char *msg_stdout_name = "./msg.stdout";
	const char *msg_stderr_name = "./msg.stderr";
	const char *msg_filter_name = "./msg.filter";
	const char *mesg = "multiplexed msg to stdout, stderr, ./msg.file, syslog local0.debug and ./msg.filtered\n";
	const char *note = "\n    Note: Can't verify syslog local0.debug. Look for:";
	void *filtered_mesg = null;
	int filtered_mesglen = 0;

	Msg *msg_stdout = msg_create_stdout();
	Msg *msg_stderr = msg_create_stderr();
	Msg *msg_file = msg_create_file(msg_file_name);
	Msg *msg_syslog = msg_create_syslog(NULL, 0, LOG_LOCAL0, LOG_DEBUG);
	Msg *msg_filter = msg_create_filter(prefix_filter, msg_create_file(msg_filter_name));
	Msg *msg_plex = msg_create_plex(msg_stdout, msg_stderr);
	int errors = 0;
	int tests = 0;
	int out, i, j, rc;

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

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

	++tests;
	if (!msg_stdout)
		++errors, printf("Test%d: failed to create msg_stdout\n", tests);
	++tests;
	if (!msg_stderr)
		++errors, printf("Test%d: failed to create msg_stderr\n", tests);
	++tests;
	if (!msg_file)
		++errors, printf("Test%d: failed to create msg_file\n", tests);
	++tests;
	if (!msg_syslog)
		++errors, printf("Test%d: failed to create msg_syslog\n", tests);
	++tests;
	if (!msg_filter)
		++errors, printf("Test%d: failed to create msg_filter\n", tests);
	++tests;
	if (!msg_plex)
		++errors, printf("Test%d: failed to create msg_plex\n", tests);
	++tests;
	if (msg_add_plex(msg_plex, msg_file) == -1)
		++errors, printf("Test%d: failed to add msg_file to msg_plex\n", tests);
	++tests;
	if (msg_add_plex(msg_plex, msg_syslog) == -1)
		++errors, printf("Test%d: failed to add msg_syslog to msg_plex\n", tests);
	++tests;
	if (msg_add_plex(msg_plex, msg_filter) == -1)
		++errors, printf("Test%d: failed to add msg_filter to msg_plex\n", tests);

	out = dup(STDOUT_FILENO);
	freopen(msg_stdout_name, "w", stdout);
	freopen(msg_stderr_name, "w", stderr);
	msg_out(msg_plex, mesg);
	msg_destroy(&msg_plex);
	dup2(out, STDOUT_FILENO);
	close(out);

	errors += verify(++tests, msg_stdout_name, mesg);
	errors += verify(++tests, msg_stderr_name, mesg);
	errors += verify(++tests, msg_file_name, mesg);

	filtered_mesglen = prefix_filter(&filtered_mesg, mesg, strlen(mesg));
	if (filtered_mesg && filtered_mesglen > 0)
	{
		errors += verify(++tests, msg_filter_name, filtered_mesg);
		mem_destroy(&filtered_mesg);
	}

	for (i = 0; syslog_facility_map[i].name; ++i)
	{
		for (j = 0; syslog_priority_map[j].name; ++j)
		{
			char buf[64];
			int facility = 0;
			int priority = 0;

			snprintf(buf, 64, "%s.%s", syslog_facility_map[i].name, syslog_priority_map[j].name);
			++tests;

			rc = syslog_parse(buf, &facility, &priority);
			if (rc == -1)
				++errors, printf("Test%d: syslog_parse(%s) failed\n", tests, buf);
			else if (facility != syslog_facility_map[i].val)
				++errors, printf("Test%d: syslog_parse(%s) failed: facility = %d (not %d)\n", tests, buf, facility, syslog_facility_map[i].val);
			else if (priority != syslog_priority_map[j].val)
				++errors, printf("Test%d: syslog_parse(%s) failed: priority = %d (not %d)\n", tests, buf, priority, syslog_priority_map[j].val);
		}
	}

	for (i = 0; syslog_facility_map[i].name; ++i)
	{
		const char *fac = syslog_facility_str(syslog_facility_map[i].val);

		++tests;
		if (strcmp(fac, syslog_facility_map[i].name))
			++errors, printf("Test%d: syslog_facility_str(%d) failed: %s (not %s)\n", tests, syslog_facility_map[i].val, fac, syslog_facility_map[i].name);
	}

	for (i = 0; syslog_priority_map[i].name; ++i)
	{
		const char *pri = syslog_priority_str(syslog_priority_map[i].val);

		++tests;
		if (strcmp(pri, syslog_priority_map[i].name))
			++errors, printf("Test%d: syslog_priority_str(%d) failed: %s (not %s)\n", tests, syslog_priority_map[i].val, pri, syslog_priority_map[i].name);
	}

	++tests;
	if (syslog_parse(NULL, NULL, NULL) != -1)
		++errors, printf("Test%d: syslog_parse(NULL) failed\n", tests);

	++tests;
	if (syslog_parse("gibberish", NULL, NULL) != -1)
		++errors, printf("Test%d: syslog_parse(\"gibberish\") failed\n", tests);

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

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

#endif

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