File: cfg-tree.c

package info (click to toggle)
syslog-ng 4.8.1-6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 20,456 kB
  • sloc: ansic: 177,631; python: 13,035; cpp: 11,611; makefile: 7,012; sh: 5,147; java: 3,651; xml: 3,344; yacc: 1,377; lex: 599; perl: 193; awk: 190; objc: 162
file content (1752 lines) | stat: -rw-r--r-- 51,217 bytes parent folder | download | duplicates (2)
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
/*
 * Copyright (c) 2002-2012 Balabit
 * Copyright (c) 1998-2012 Balázs Scheidler
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * As an additional exemption you are allowed to compile & link against the
 * OpenSSL libraries as published by the OpenSSL project. See the file
 * COPYING for details.
 *
 */

#include "cfg-tree.h"
#include "logmpx.h"
#include "logpipe.h"
#include "metrics-pipe.h"
#include "mainloop.h"

#include <string.h>

static void _log_expr_node_free(LogExprNode *self);

LogExprNode *
log_expr_node_ref(LogExprNode *self)
{
  g_assert(!self || g_atomic_counter_get(&self->ref_cnt) > 0);

  if (self)
    {
      g_atomic_counter_inc(&self->ref_cnt);
    }
  return self;
}

LogExprNode *
log_expr_node_unref(LogExprNode *self)
{
  g_assert(!self || g_atomic_counter_get(&self->ref_cnt));

  if (self && (g_atomic_counter_dec_and_test(&self->ref_cnt)))
    {
      _log_expr_node_free(self);
      return NULL;
    }
  return self;
}

/*
 * Return the textual representation of a node content type.
 */
const gchar *
log_expr_node_get_content_name(gint content)
{
  switch (content)
    {
    case ENC_PIPE:
      return "log";
    case ENC_SOURCE:
      return "source";
    case ENC_FILTER:
      return "filter";
    case ENC_PARSER:
      return "parser";
    case ENC_REWRITE:
      return "rewrite";
    case ENC_DESTINATION:
      return "destination";
    default:
      g_assert_not_reached();
      break;
    }
}

/*
 * Return the textual representation of a node layout.
 */
const gchar *
log_expr_node_get_layout_name(gint layout)
{
  switch (layout)
    {
    case ENL_SINGLE:
      return "single";
    case ENL_REFERENCE:
      return "reference";
    case ENL_SEQUENCE:
      return "sequence";
    case ENL_JUNCTION:
      return "junction";
    case ENL_CONDITIONAL:
      return "conditional";
    default:
      g_assert_not_reached();
      break;
    }
}

/* return the top-most rule that matches content. This is used to
 * query the enclosing rule for a given LogExprNode. It is looking up
 * the top-most node, so that we use the name of the enclosing block
 * that the user specified. In-line defined, and thus anonymous
 * expressions are automatically named. In that case this function
 * will return a node matching @content but without an actual name.
 */
LogExprNode *
log_expr_node_get_container_rule(LogExprNode *self, gint content)
{
  LogExprNode *node, *result = NULL;

  node = self->parent;
  while (node)
    {
      if (node->content == content)
        {
          result = node;
        }
      node = node->parent;
    }
  return result;
}

/**
 * log_expr_node_append:
 * @a: first LogExprNode
 * @b: second LogExprNode
 *
 * This function appends @b to @a in a linked list using the ep_next field
 * in LogExprNode.
 **/
void
log_expr_node_append(LogExprNode *a, LogExprNode *b)
{
  a->next = b;
}

LogExprNode *
log_expr_node_append_tail(LogExprNode *a, LogExprNode *b)
{
  if (a)
    {
      LogExprNode *p = a;
      while (p->next)
        p = p->next;
      log_expr_node_append(p, b);
      return a;
    }
  return b;
}

/*
 * Format the location information for a LogExprNode. For nodes that
 * have no location information, the parent is considered, this way
 * always returning something close to the location that defined the
 * node.
 */
const gchar *
log_expr_node_format_location(LogExprNode *self, gchar *buf, gsize buf_len)
{
  LogExprNode *node = self;

  while (node)
    {
      if (node->line || node->column)
        {
          g_snprintf(buf, buf_len, "%s:%d:%d", self->filename ? : "#buffer", node->line, node->column);
          break;
        }
      node = node->parent;
    }
  if (!node)
    g_strlcpy(buf, "#unknown", buf_len);
  return buf;
}

EVTTAG *
log_expr_node_location_tag(LogExprNode *self)
{
  gchar buf[128];

  return evt_tag_str("location", log_expr_node_format_location(self, buf, sizeof(buf)));
}

/*
 * Set the list of children of a LogExprNode. It automatically updates
 * the children's "parent" pointers so that the tree can be traversed
 * upwards too.
 */
void
log_expr_node_set_children(LogExprNode *self, LogExprNode *children)
{
  LogExprNode *ep;

  /* we don't currently support setting the children list multiple
   * times. no inherent reason, just the proper free function would
   * need to be written, until then this assert would reveal the case
   * quite fast.
   */

  g_assert(self->children == NULL);

  for (ep = children; ep; ep = ep->next)
    ep->parent = self;

  self->children = children;
}

/*
 * Set the object associated with a node. The "object" member is used
 * to store the LogPipe instance associated with ENL_SINGLE/ENC_PIPE
 * nodes.
 */
void
log_expr_node_set_object(LogExprNode *self, gpointer object, GDestroyNotify destroy)
{
  self->object = object;
  self->object_destroy = destroy;
}

/*
 * The aux object is the secondary object associated with a node, it
 * is mostly unused, except for nodes storing source and destination
 * statements, in which case this contains a reference to the last
 * item of the compiled sequence (for sources) or the first item of
 * the compiled sequence (destinations).
 *
 * This mechanism is used to avoid having to clone source/destination
 * pipes, which operation they don't support.
 */
void
log_expr_node_set_aux(LogExprNode *self, gpointer aux, GDestroyNotify destroy)
{
  self->aux = aux;
  self->aux_destroy = destroy;
}

void
log_expr_node_set_name(LogExprNode *self, const gchar *name)
{
  g_free(self->name);
  self->name = g_strdup(name);
}

/**
 * log_expr_node_new:
 * @layout: layout of the children (ENL_*)
 * @content: what kind of expression this node stores (ENC_*)
 * @name: name of this rule (optional)
 * @children: child nodes
 * @flags: a combination of LC_* flags as specified by the administrator
 * @yylloc: the lexer location in the configuration file.
 *
 * This function constructs a LogExprNode object which encapsulates a
 * log expression in the configuration. See the note in cfg-tree.h for
 * more information about LogExprNode objects and log expressions.
 **/
LogExprNode *
log_expr_node_new(gint layout, gint content, const gchar *name, LogExprNode *children, guint32 flags, CFG_LTYPE *yylloc)
{
  LogExprNode *self = g_new0(LogExprNode, 1);

  g_atomic_counter_set(&self->ref_cnt, 1);

  self->layout = layout;
  self->content = content;
  self->name = g_strdup(name);
  log_expr_node_set_children(self, children);
  self->flags = flags;
  if (yylloc)
    {
      self->filename = g_strdup(yylloc->name);
      self->line = yylloc->first_line;
      self->column = yylloc->first_column;
    }
  return self;
}

/**
 * log_expr_node_free:
 * @self: LogExprNode instance
 *
 * This function frees the LogExprNode object encapsulating a log
 * expression node pointed to by @self.
 **/
static void
_log_expr_node_free(LogExprNode *self)
{
  LogExprNode *next, *p;

  for (p = self->children ; p; p = next)
    {
      next = p->next;
      log_expr_node_unref(p);
    }
  if (self->object && self->object_destroy)
    self->object_destroy(self->object);
  if (self->aux && self->aux_destroy)
    self->aux_destroy(self->aux);
  g_free(self->name);
  g_free(self->filename);
  g_free(self);
}

LogExprNode *
log_expr_node_new_pipe(LogPipe *pipe, CFG_LTYPE *yylloc)
{
  LogExprNode *node = log_expr_node_new(ENL_SINGLE, ENC_PIPE, NULL, NULL, 0, yylloc);

  log_expr_node_set_object(node, pipe, (GDestroyNotify) log_pipe_unref);
  return node;
}

LogExprNode *
log_expr_node_new_source(const gchar *name, LogExprNode *children, CFG_LTYPE *yylloc)
{
  return log_expr_node_new(ENL_SEQUENCE, ENC_SOURCE, name, children, 0, yylloc);
}

LogExprNode *
log_expr_node_new_source_reference(const gchar *name, CFG_LTYPE *yylloc)
{
  return log_expr_node_new(ENL_REFERENCE, ENC_SOURCE, name, NULL, 0, yylloc);
}

LogExprNode *
log_expr_node_new_destination(const gchar *name, LogExprNode *children, CFG_LTYPE *yylloc)
{
  return log_expr_node_new(ENL_SEQUENCE, ENC_DESTINATION, name, children, 0, yylloc);
}

LogExprNode *
log_expr_node_new_destination_reference(const gchar *name, CFG_LTYPE *yylloc)
{
  return log_expr_node_new(ENL_REFERENCE, ENC_DESTINATION, name, NULL, 0, yylloc);
}

LogExprNode *
log_expr_node_new_filter(const gchar *name, LogExprNode *child, CFG_LTYPE *yylloc)
{
  return log_expr_node_new(ENL_SEQUENCE, ENC_FILTER, name, child, 0, yylloc);
}

LogExprNode *
log_expr_node_new_filter_reference(const gchar *name, CFG_LTYPE *yylloc)
{
  return log_expr_node_new(ENL_REFERENCE, ENC_FILTER, name, NULL, 0, yylloc);
}

LogExprNode *
log_expr_node_new_parser(const gchar *name, LogExprNode *children, CFG_LTYPE *yylloc)
{
  return log_expr_node_new(ENL_SEQUENCE, ENC_PARSER, name, children, 0, yylloc);
}

LogExprNode *
log_expr_node_new_parser_reference(const gchar *name, CFG_LTYPE *yylloc)
{
  return log_expr_node_new(ENL_REFERENCE, ENC_PARSER, name, NULL, 0, yylloc);
}

LogExprNode *
log_expr_node_new_rewrite(const gchar *name, LogExprNode *children, CFG_LTYPE *yylloc)
{
  return log_expr_node_new(ENL_SEQUENCE, ENC_REWRITE, name, children, 0, yylloc);
}

LogExprNode *
log_expr_node_new_rewrite_reference(const gchar *name, CFG_LTYPE *yylloc)
{
  return log_expr_node_new(ENL_REFERENCE, ENC_REWRITE, name, NULL, 0, yylloc);
}

LogExprNode *
log_expr_node_new_log(LogExprNode *children, guint32 flags, CFG_LTYPE *yylloc)
{
  return log_expr_node_new(ENL_SEQUENCE, ENC_PIPE, NULL, children, flags, yylloc);
}

LogExprNode *
log_expr_node_new_sequence(LogExprNode *children, CFG_LTYPE *yylloc)
{
  return log_expr_node_new(ENL_SEQUENCE, ENC_PIPE, NULL, children, 0, yylloc);
}

LogExprNode *
log_expr_node_new_junction(LogExprNode *children, CFG_LTYPE *yylloc)
{
  return log_expr_node_new(ENL_JUNCTION, ENC_PIPE, NULL, children, 0, yylloc);
}

LogExprNode *
log_expr_node_new_source_junction(LogExprNode *children, CFG_LTYPE *yylloc)
{
  return log_expr_node_new(ENL_JUNCTION, ENC_SOURCE, NULL, children, 0, yylloc);
}

LogExprNode *
log_expr_node_new_destination_junction(LogExprNode *children, CFG_LTYPE *yylloc)
{
  return log_expr_node_new(ENL_JUNCTION, ENC_DESTINATION, NULL, children, 0, yylloc);
}

LogExprNode *
log_expr_node_new_conditional(LogExprNode *filter_expr,
                              LogExprNode *true_expr, LogExprNode *false_expr,
                              CFG_LTYPE *yylloc)
{
  LogExprNode *children = true_expr;

  log_expr_node_append(true_expr, false_expr);
  log_expr_node_append(false_expr, filter_expr);
  return log_expr_node_new(ENL_CONDITIONAL, ENC_PIPE, NULL, children, 0, yylloc);
}

/****************************************************************************
 * Functions related to conditional nodes
 *
 * These are higher-level functions that map if-elif-else structure to
 * LogExprNode instances.  Rather than using a higher level data struct
 * which then generates LogExprNode instances, we represent/manipulate the
 * if-elif-else structure right within LogExprNode.
 *
 * A conditional node is simply a junction with two children:
 *
 *     1) the first child is the "TRUE" branch, with the filter expression
 *     attached and the final flag
 *
 *     2) the second child is the "FALSE" branch, possibly empty, but also
 *     the final flag.
 *
 * Basically this is the equivalent to:
 *
 *     junction {
 *       channel {
 *         filter { EXPRESSION; };
 *         flags(final);
 *       };
 *       channel {
 *         flags(final);
 *       };
 *     };
 *
 * When parsing an if block, we generate both children immediately, with the
 * empty 2nd channel, and then if an elif or else comes, the FALSE branch
 * gets replaced.
 *
 * The series of if-elif-else sequences is represented by its first
 * LogExprNode (e.g.  the first if).  When we need to add an else or elif,
 * we would have to locate the last dangling if statement based on this
 * first LogExprNode.  The alternative would have been to store the last if
 * statement in a variable, however that becomes pretty complicated if we
 * need to handle nesting.
 *
 ****************************************************************************/

static LogExprNode *
log_expr_node_conditional_get_true_branch(LogExprNode *node)
{
  g_assert(node->layout == ENL_CONDITIONAL);

  LogExprNode *branches = node->children;

  g_assert(branches != NULL);
  g_assert(branches->next != NULL);

  /* first child */
  return branches;
}

static LogExprNode *
log_expr_node_conditional_get_false_branch(LogExprNode *node)
{
  g_assert(node->layout == ENL_CONDITIONAL);

  LogExprNode *branches = node->children;
  g_assert(branches != NULL);
  g_assert(branches->next != NULL);

  /* second child */
  return branches->next;
}

static gboolean
log_expr_node_conditional_is_branch_empty(LogExprNode *node)
{
  return node->children == NULL;
}

/* this function locates the last dangling if, based on the very first if
 * statement in a series of ifs at the same level */
static LogExprNode *
_locate_last_conditional_along_nested_else_blocks(LogExprNode *head)
{
  while (1)
    {
      g_assert(log_expr_node_conditional_get_true_branch(head) != NULL);
      g_assert(log_expr_node_conditional_get_false_branch(head) != NULL);

      LogExprNode *false_branch = log_expr_node_conditional_get_false_branch(head);

      /* check if this is the last else */
      if (log_expr_node_conditional_is_branch_empty(false_branch))
        return head;
      head = false_branch->children;
    }
  g_assert_not_reached();
}

/* change the FALSE branch (e.g. the else case) of the last dangling if, specified by the head element */
void
log_expr_node_conditional_set_false_branch_of_the_last_if(LogExprNode *conditional_head_node, LogExprNode *false_expr)
{
  LogExprNode *conditional_node = _locate_last_conditional_along_nested_else_blocks(conditional_head_node);
  LogExprNode *branches = conditional_node->children;

  /* a conditional branch always have three children (see the constructor
   * below), the first one is the "true" branch and the second one is the
   * "false" branch, as they are constructed as final log channels with
   * filter statement in the first one as the "if" expression.  */

  /* assert that we only have two children */
  g_assert(branches != NULL);
  g_assert(branches->next != NULL);

  LogExprNode *true_expr = branches;
  LogExprNode *old_false_expr = branches->next;
  LogExprNode *filter_expr = branches->next->next;

  /* construct the new false branch */
  LogExprNode *new_false_expr = log_expr_node_new_log(
                                  false_expr,
                                  LC_FINAL,
                                  NULL
                                );

  /* unlink and free the old one */

  g_assert(!filter_expr || filter_expr->parent == conditional_node);
  new_false_expr->parent = conditional_node;

  log_expr_node_append(true_expr, new_false_expr);
  log_expr_node_append(new_false_expr, filter_expr);

  log_expr_node_unref(old_false_expr);
}

/*
 */
LogExprNode *
log_expr_node_new_simple_conditional(LogExprNode *filter_expr, LogExprNode *true_expr, CFG_LTYPE *yylloc)
{

  /*
   *  channel {
   *    true_expr;
   *    flags(final);
   *  };
   */
  true_expr->flags |= LC_FINAL;

  /*
   *  channel {
   *    flags(final);
   *  };
   *
   * NOTE: the false branch may be modified later, once an else or elif is
   * encountered in the configuration, see
   * log_expr_node_conditional_set_false_branch_of_the_last_if() function
   * above.
   */

  LogExprNode *false_expr = log_expr_node_new_log(
                              NULL,
                              LC_FINAL,
                              NULL
                            );
  return log_expr_node_new_conditional(log_expr_node_new_filter(NULL, filter_expr, yylloc),
                                       true_expr, false_expr, yylloc);
}

LogExprNode *
log_expr_node_new_compound_conditional(LogExprNode *block, CFG_LTYPE *yylloc)
{
  /*
   *  channel {
   *    filtering_and_parsing_expr;
   *    flags(final);
   *  };
   */

  LogExprNode *true_expr = block;

  true_expr->flags |= LC_FINAL;

  /*
   *  channel {
   *    flags(final);
   *  };
   *
   * NOTE: the false branch may be modified later, once an else or elif is
   * encountered in the configuration, see
   * log_expr_node_conditional_set_false_branch_of_the_last_if() function
   * above.
   */

  LogExprNode *false_expr = log_expr_node_new_log(
                              NULL,
                              LC_FINAL,
                              NULL
                            );
  return log_expr_node_new_conditional(NULL, true_expr, false_expr, yylloc);

}

/****************************************************************************/

gint
log_expr_node_lookup_flag(const gchar *flag)
{
  if (strcmp(flag, "catch-all") == 0 || strcmp(flag, "catchall") == 0)
    return LC_CATCHALL;
  else if (strcmp(flag, "fallback") == 0)
    return LC_FALLBACK;
  else if (strcmp(flag, "final") == 0)
    return LC_FINAL;
  else if (strcmp(flag, "flow-control") == 0)
    return LC_FLOW_CONTROL;
  else if (strcmp(flag, "drop-unmatched") == 0)
    {
      msg_warning_once("WARNING: The drop-unmatched flag has been removed starting with " VERSION_4_1 ". "
                       "Setting it has no effect on the log path");
      return 0;
    }
  msg_error("Unknown log statement flag", evt_tag_str("flag", flag));
  return 0;
}

static void
_log_pipe_unref(void *s)
{
  log_pipe_unref(s);
}

static void
cfg_tree_start_registering_pipes_with_persist_name(CfgTree *self)
{
  main_loop_assert_main_thread();

  self->pipes_with_persis_name = g_hash_table_new_full(NULL, NULL, NULL, _log_pipe_unref);
}

static void
cfg_tree_stop_registering_pipes_with_persist_name(CfgTree *self)
{
  if (self->pipes_with_persis_name)
    {
      main_loop_assert_main_thread();

      g_hash_table_unref(self->pipes_with_persis_name);
      self->pipes_with_persis_name = NULL;
    }
}

void
cfg_tree_register_initialized_pipe(CfgTree *self, LogPipe *s)
{
  if (self->pipes_with_persis_name)
    {
      main_loop_assert_main_thread();

      if (FALSE == g_hash_table_contains(self->pipes_with_persis_name, s) && log_pipe_get_persist_name(s))
        {
          log_pipe_ref(s);
          g_hash_table_add(self->pipes_with_persis_name, s);
        }
    }
}

void
cfg_tree_deregister_initialized_pipe(CfgTree *self, LogPipe *s)
{
  if (self->pipes_with_persis_name)
    {
      main_loop_assert_main_thread();

      if (g_hash_table_contains(self->pipes_with_persis_name, s))
        g_hash_table_remove(self->pipes_with_persis_name, s);
    }
}

static LogPipe *
cfg_tree_assoc_pipe(CfgTree *self, LogExprNode *node, LogPipe *pipe, const gchar *info)
{
  pipe->expr_node = node;
  g_ptr_array_add(self->initialized_pipes, pipe);
  log_pipe_add_info(pipe, info);
  return pipe;
}

static LogPipe *
cfg_tree_new_pipe(CfgTree *self, LogExprNode *related_expr, const gchar *info)
{
  return cfg_tree_assoc_pipe(self, related_expr, log_pipe_new(self->cfg), info);
}

static LogMultiplexer *
cfg_tree_new_mpx(CfgTree *self, LogExprNode *related_expr, const gchar *info)
{
  return (LogMultiplexer *) cfg_tree_assoc_pipe(self, related_expr, &log_multiplexer_new(self->cfg)->super, info);
}

MetricsPipe *
cfg_tree_new_metrics_pipe(CfgTree *self, LogExprNode *related_expr)
{
  return (MetricsPipe *) cfg_tree_assoc_pipe(self, related_expr,
                                             &metrics_pipe_new(self->cfg, related_expr->name)->super,
                                             "metrics-pipe");
}

static gchar *
_format_anon_rule_name(CfgTree *self, gint content)
{
  return g_strdup_printf("#anon-%s%d", log_expr_node_get_content_name(content), self->anon_counters[content]++);
}

/*
 * Return the name of the rule that contains a LogExprNode. Generates
 * one automatically for anonymous log expressions.
 *
 * NOTE: this returns an allocated string, the caller must free that.
 */
gchar *
cfg_tree_get_rule_name(CfgTree *self, gint content, LogExprNode *node)
{
  gchar *rule_name;

  if (node)
    {
      LogExprNode *rule = log_expr_node_get_container_rule(node, content);
      if (!rule->name)
        rule->name = _format_anon_rule_name(self, content);
      rule_name = g_strdup(rule->name);
    }
  else
    {
      rule_name = _format_anon_rule_name(self, content);
    }

  return rule_name;
}

/*
 * Return a unique the name associated with a LogExprNode. It is of
 * the format <rule>#<seqid>.
 *
 * NOTE: this returns an allocated string, the caller must free that.
 */
gchar *
cfg_tree_get_child_id(CfgTree *self, gint content, LogExprNode *node)
{
  gchar *rule_name = cfg_tree_get_rule_name(self, content, node);
  gint cur_child_id;
  gchar *res;

  if (node)
    {
      LogExprNode *rule = log_expr_node_get_container_rule(node, content);
      cur_child_id = rule->child_id++;
    }
  else
    cur_child_id = 0;
  res = g_strdup_printf("%s#%d", rule_name, cur_child_id);
  g_free(rule_name);
  return res;
}

/* hash foreach function to add all source objects to catch-all rules */
static void
cfg_tree_add_all_sources(gpointer key, gpointer value, gpointer user_data)
{
  gpointer *args = (gpointer *) user_data;
  LogExprNode *referring_rule = args[1];
  LogExprNode *rule = (LogExprNode *) value;

  if (rule->content != ENC_SOURCE)
    return;

  /* prepend a source reference */
  referring_rule->children = log_expr_node_append_tail(log_expr_node_new_source_reference(rule->name, NULL),
                                                       referring_rule->children);
}

static gboolean
cfg_tree_compile_node(CfgTree *self, LogExprNode *node,
                      LogPipe **outer_pipe_head, LogPipe **outer_pipe_tail);

static gboolean
cfg_tree_compile_single(CfgTree *self, LogExprNode *node,
                        LogPipe **outer_pipe_head, LogPipe **outer_pipe_tail)
{
  LogPipe *pipe;

  g_assert(node->content == ENC_PIPE);

  /* LC_XXX flags are currently only implemented for sequences, ensure that the grammar enforces this. */
  g_assert(node->flags == 0);

  pipe = node->object;

  if ((pipe->flags & PIF_INLINED) == 0)
    {
      /* first reference to the pipe uses the same instance, further ones will get cloned */
      pipe->flags |= PIF_INLINED;
      /* The pipe object is borrowed, so the reference counter must be increased. */
      log_pipe_ref(pipe);
    }
  else
    {
      /* ok, we are using this pipe again, it needs to be cloned */
      pipe = log_pipe_clone(pipe);
      if (!pipe)
        {
          msg_error("Error cloning pipe into its reference point, probably the element in question is not meant to be used in this situation",
                    log_expr_node_location_tag(node));
          goto error;
        }
      pipe->flags |= PIF_INLINED;
    }
  g_ptr_array_add(self->initialized_pipes, pipe);
  pipe->expr_node = node;

  if ((pipe->flags & PIF_SOURCE) == 0)
    *outer_pipe_head = pipe;
  *outer_pipe_tail = pipe;
  return TRUE;

error:
  return FALSE;
}

static gboolean
cfg_tree_compile_reference(CfgTree *self, LogExprNode *node,
                           LogPipe **outer_pipe_head, LogPipe **outer_pipe_tail)
{
  LogExprNode *referenced_node;

  /* LC_XXX flags are currently only implemented for sequences, ensure that the grammar enforces this. */
  g_assert(node->flags == 0);

  if (!node->object)
    {
      referenced_node = cfg_tree_get_object(self, node->content, node->name);
    }
  else
    referenced_node = node->object;

  if (!referenced_node)
    {
      msg_error("Error resolving reference",
                evt_tag_str("content", log_expr_node_get_content_name(node->content)),
                evt_tag_str("name", node->name),
                log_expr_node_location_tag(node));
      goto error;
    }

  switch (referenced_node->content)
    {
    case ENC_SOURCE:
    {
      LogMultiplexer *mpx;
      LogPipe *sub_pipe_head = NULL, *sub_pipe_tail = NULL;
      LogPipe *attach_pipe = NULL;

      if (!referenced_node->aux)
        {
          if (!cfg_tree_compile_node(self, referenced_node, &sub_pipe_head, &sub_pipe_tail))
            goto error;
          log_expr_node_set_aux(referenced_node, log_pipe_ref(sub_pipe_tail), (GDestroyNotify) log_pipe_unref);
        }
      else
        {
          sub_pipe_tail = referenced_node->aux;
        }

      attach_pipe = cfg_tree_new_pipe(self, node, "source-attach");

      if (sub_pipe_tail)
        {
          /* when the source is empty, we'll get a NULL tail in
           * sub_pipe_tail.  We handle that by simply not connecting
           * anything to the attachment point */

          if (!sub_pipe_tail->pipe_next)
            {
              mpx = cfg_tree_new_mpx(self, referenced_node, "mpx(source)");
              log_pipe_append(sub_pipe_tail, &mpx->super);
            }
          else
            {
              mpx = (LogMultiplexer *) sub_pipe_tail->pipe_next;
            }
          log_multiplexer_add_next_hop(mpx, attach_pipe);
        }
      *outer_pipe_head = NULL;
      *outer_pipe_tail = attach_pipe;
      break;
    }
    case ENC_DESTINATION:
    {
      LogMultiplexer *mpx;
      LogPipe *sub_pipe_head = NULL, *sub_pipe_tail = NULL;

      if (!referenced_node->aux)
        {
          if (!cfg_tree_compile_node(self, referenced_node, &sub_pipe_head, &sub_pipe_tail))
            goto error;
          log_expr_node_set_aux(referenced_node, log_pipe_ref(sub_pipe_head), (GDestroyNotify) log_pipe_unref);
        }
      else
        {
          sub_pipe_head = referenced_node->aux;
        }

      /* We need a new LogMultiplexer instance for two reasons:

         1) we need to link something into the sequence, all
         reference based destination invocations need a separate
         LogPipe

         2) we have to fork downwards to the destination, it may
         change the message but we need the original one towards
         our next chain
      */

      mpx = cfg_tree_new_mpx(self, node, "mpx(destination-reference)");
      log_multiplexer_disable_delivery_propagation(mpx);

      if (sub_pipe_head)
        {
          /* when the destination is empty */
          log_multiplexer_add_next_hop(mpx, sub_pipe_head);
        }
      *outer_pipe_head = &mpx->super;
      *outer_pipe_tail = NULL;
      break;
    }
    default:
      return cfg_tree_compile_node(self, referenced_node, outer_pipe_head, outer_pipe_tail);
    }
  return TRUE;

error:
  return FALSE;
}

static void
cfg_tree_propagate_expr_node_properties_to_pipe(LogExprNode *node, LogPipe *pipe)
{
  if (node->flags & LC_FALLBACK)
    pipe->flags |= PIF_BRANCH_FALLBACK;

  if (node->flags & LC_FINAL)
    pipe->flags |= PIF_BRANCH_FINAL;

  if (node->flags & LC_FLOW_CONTROL)
    pipe->flags |= PIF_HARD_FLOW_CONTROL;

  if (!pipe->expr_node)
    pipe->expr_node = node;
}

static gboolean
_is_log_path_name_unique(CfgTree *self, const LogExprNode *node)
{
  if (g_hash_table_contains(self->log_path_names, node->name))
    return FALSE;

  g_hash_table_insert(self->log_path_names, g_strdup(node->name), NULL);
  return TRUE;
}

/**
 * cfg_tree_compile_sequence:
 *
 * Construct the sequential part of LogPipe pipeline as specified by
 * the user. The sequential part is where no branches exist, pipes are
 * merely linked to each other. This is in contrast with a "junction"
 * where the processing is forked into different branches. Junctions
 * are built using cfg_tree_compile_junction() above.
 *
 * The configuration is parsed into a series of LogExprNode
 * elements, each giving a reference to a source, filter, parser,
 * rewrite and destination. This function connects these so that their
 * log_pipe_queue() method will dispatch the message correctly (which
 * in turn boils down to setting the LogPipe->next member).
 *
 * The tree like structure is created using LogMultiplexer instances,
 * pipes are connected back with a simple LogPipe instance that only
 * forwards messages.
 *
 * The next member pointer is not holding a reference, but can be
 * assumed to be kept alive as long as the configuration is running.
 *
 * Parameters:
 * @self: the CfgTree instance
 * @rule: the series of LogExprNode instances encapsulates as a LogExprNode
 * @outer_pipe_tail: the last LogPipe to be used to chain further elements to this sequence
 * @cfg: GlobalConfig instance
 * @toplevel: whether this rule is a top-level one.
 **/
static gboolean
cfg_tree_compile_sequence(CfgTree *self, LogExprNode *node,
                          LogPipe **outer_pipe_head, LogPipe **outer_pipe_tail)
{
  LogExprNode *ep;
  LogPipe
  *first_pipe,   /* the head of the constructed pipeline */
  *last_pipe;    /* the current tail of the constructed pipeline */
  LogPipe *source_join_pipe = NULL;
  gboolean node_properties_propagated = FALSE;

  if ((node->flags & LC_CATCHALL) != 0)
    {
      /* the catch-all resolution code clears this flag */

      msg_error("Error in configuration, catch-all flag can only be specified for top-level log statements");
      goto error;
    }

  if (node->content == ENC_PIPE && node->name && !_is_log_path_name_unique(self, node))
    {
      msg_error("Error in configuration, duplicate log path definition",
                evt_tag_str("log_path_name", node->name),
                log_expr_node_location_tag(node));
      goto error;
    }

  /* the loop below creates a sequence of LogPipe instances which
   * essentially execute the user configuration once it is
   * started.
   *
   * The input of this is a log expression, denoted by a tree of
   * LogExprNode structures, built by the parser. We are storing the
   * sequence as a linked list, pipes are linked with their "next"
   * field.
   *
   * The head of this list is pointed to by @first_pipe, the current
   * end is known as @last_pipe.
   *
   * In case the sequence starts with a source LogPipe (PIF_SOURCE
   * flag), the head of the list is _not_ tracked, in that case
   * first_pipe is NULL.
   *
   */

  first_pipe = last_pipe = NULL;

  for (ep = node->children; ep; ep = ep->next)
    {
      LogPipe *sub_pipe_head = NULL, *sub_pipe_tail = NULL;

      if (!cfg_tree_compile_node(self, ep, &sub_pipe_head, &sub_pipe_tail))
        goto error;

      /* add pipe to the current pipe_line, e.g. after last_pipe, update last_pipe & first_pipe */
      if (sub_pipe_head)
        {
          if (!node_properties_propagated)
            {
              cfg_tree_propagate_expr_node_properties_to_pipe(node, sub_pipe_head);
              node_properties_propagated = TRUE;
            }
          if (!first_pipe && !last_pipe)
            {
              /* we only remember the first pipe in case we're not in
               * source mode. In source mode, only last_pipe is set */

              first_pipe = sub_pipe_head;
            }

          if (last_pipe)
            {
              g_assert(last_pipe->pipe_next == NULL);
              log_pipe_append(last_pipe, sub_pipe_head);
            }

          if (sub_pipe_tail)
            {
              last_pipe = sub_pipe_tail;
            }
          else
            {
              last_pipe = sub_pipe_head;
              /* look for the final pipe */
              while (last_pipe->pipe_next)
                {
                  last_pipe = last_pipe->pipe_next;
                }
            }
          sub_pipe_head = NULL;
        }
      else if (sub_pipe_tail)
        {
          /* source pipe */

          if (first_pipe)
            {
              msg_error("Error compiling sequence, source-pipe follows a non-source one, please list source references/definitions first",
                        log_expr_node_location_tag(ep));
              goto error;
            }

          if (!source_join_pipe)
            {
              if (node->content == ENC_PIPE && node->name)
                {
                  MetricsPipe *metrics_pipe = cfg_tree_new_metrics_pipe(self, node);
                  source_join_pipe = last_pipe = &metrics_pipe->super;
                }
              else
                {
                  source_join_pipe = last_pipe = cfg_tree_new_pipe(self, node, "source-join");
                }
            }
          log_pipe_append(sub_pipe_tail, source_join_pipe);
        }
    }

  if (node->content == ENC_PIPE && node->name && first_pipe)
    {
      MetricsPipe *metrics_pipe = cfg_tree_new_metrics_pipe(self, node);
      log_pipe_append(&metrics_pipe->super, first_pipe);
      first_pipe = &metrics_pipe->super;
    }

  if (!first_pipe && !last_pipe)
    {
      /* this is an empty sequence, insert a do-nothing LogPipe */
      first_pipe = last_pipe = cfg_tree_new_pipe(self, node, "noop");
    }


  /* NOTE: if flow control is enabled, then we either need to have an
   * embedded log statement (in which case first_pipe is set, as we're not
   * starting with sources), OR we created a source_join_pipe already.
   *
   */

  g_assert(((node->flags & LC_FLOW_CONTROL) && (first_pipe || source_join_pipe)) ||
           !(node->flags & LC_FLOW_CONTROL));

  if (!node_properties_propagated)
    {
      /* we never encountered anything that would produce a head_pipe, e.g.
       * this sequence only contains a source and nothing else.  In that
       * case, apply node flags to the last pipe.  It should be picked up
       * when LogMultiplexer iterates over the branch in
       * log_multiplexer_init() as long as last_pipe is linked into the
       * pipe_next list and is not forked off at a LogMultiplexer.
       * */

      cfg_tree_propagate_expr_node_properties_to_pipe(node, last_pipe);
      node_properties_propagated = TRUE;
    }

  if (node->content == ENC_DESTINATION)
    {
      /* We want to leave pipe-next available to use for
         destinations. Config graph uses pipe-next to pass messages forward
         in a sequence layout. But pipe-next might be overridden (for
         example network destination with LogWriter) hence disjointing
         the config graph.

         This patch links destinations in T form, instead of single link.

         * (endpoint of sequence)
         |
         V
         * (multiplexer) -(next-hop)-> destination -(pipe-next*)-> logwriter
         |
         (pipe-next)
         |
         V
         * (rest of the sequence)
         That way destinations are free to use the pipe-next*
      */

      last_pipe = first_pipe;
    }

  *outer_pipe_tail = last_pipe;
  *outer_pipe_head = first_pipe;
  return TRUE;
error:

  /* we don't need to free anything, everything we allocated is recorded in
   * @self, thus will be freed whenever cfg_tree_free is called */

  return FALSE;
}

/**
 * cfg_tree_compile_junction():
 *
 * This function builds a junction within the configuration. A
 * junction is where processing is forked into several branches, each
 * doing its own business, and then the end of each branch is
 * collected at the end so that further processing can be done on the
 * combined output of each log branch.
 *
 *       /-- branch --\
 *      /              \
 *  ---+---- branch ----+---
 *      \              /
 *       \-- branch --/
 **/
static gboolean
cfg_tree_compile_junction(CfgTree *self,
                          LogExprNode *node,
                          LogPipe **outer_pipe_head, LogPipe **outer_pipe_tail)
{
  LogExprNode *ep;
  LogPipe *join_pipe = NULL;    /* the pipe where parallel branches are joined in a junction */
  LogMultiplexer *fork_mpx = NULL;

  /* LC_XXX flags are currently only implemented for sequences, ensure that the grammar enforces this. */
  g_assert(node->flags == 0);

  for (ep = node->children; ep; ep = ep->next)
    {
      LogPipe *sub_pipe_head = NULL, *sub_pipe_tail = NULL;
      gboolean is_first_branch = (ep == node->children);

      if (!cfg_tree_compile_node(self, ep, &sub_pipe_head, &sub_pipe_tail))
        goto error;

      if (sub_pipe_head)
        {
          /* ep is an intermediate LogPipe or a destination, we have to fork */

          if (!is_first_branch && !fork_mpx)
            {
              msg_error("Error compiling junction, source and non-source branches are mixed",
                        log_expr_node_location_tag(ep));
              goto error;
            }
          if (!fork_mpx)
            {
              fork_mpx = cfg_tree_new_mpx(self, node,
                                          node->content == ENC_DESTINATION
                                          ? "mpx(destination-junction)"
                                          : (node->content == ENC_SOURCE ? "mpx(source-junction)" : "mpx(junction)"));

              if (node->content == ENC_DESTINATION)
                log_multiplexer_disable_delivery_propagation(fork_mpx);
              *outer_pipe_head = &fork_mpx->super;
            }
          log_multiplexer_add_next_hop(fork_mpx, sub_pipe_head);
        }
      else
        {
          /* ep is a "source" LogPipe (cause no sub_pipe_head returned by compile_node). */

          if (fork_mpx)
            {
              msg_error("Error compiling junction, source and non-source branches are mixed",
                        log_expr_node_location_tag(ep));
              goto error;
            }
        }

      if (sub_pipe_tail && outer_pipe_tail)
        {
          if (!join_pipe)
            {
              join_pipe = cfg_tree_new_pipe(self, node, "junction-end");
            }
          log_pipe_append(sub_pipe_tail, join_pipe);

        }
    }

  if (fork_mpx)
    {

      /* Groups of source drivers are enclosed into junctions, so that we
       * can attach to their tail end and do additional processing on the
       * emitted messages.
       *
       * In the case of sources, messages do not enter the junction in the
       * front, through the multiplexer, rather these messages originate from
       * one of the source drivers.
       *
       * In this scenario, the junction does not have a multiplexer in front
       * (hence fork_mpx == NULL) and this also means that we don't have to
       * close the loop.
       *
       * This conditional is only executed for non-source junctions, in
       * which case we do have a fork_mpx and we need to set
       * PIF_JUNCTION_END on the tail of the junction.
       */

      g_assert(node->content != ENC_SOURCE);
      join_pipe->flags |= PIF_JUNCTION_END;
    }

  if (outer_pipe_tail)
    *outer_pipe_tail = join_pipe;
  return TRUE;
error:

  /* we don't need to free anything, everything we allocated is recorded in
   * @self, thus will be freed whenever cfg_tree_free is called */

  return FALSE;
}

/**
 * cfg_tree_compile_conditional():
 **/
static gboolean
cfg_tree_compile_conditional(CfgTree *self,
                             LogExprNode *node,
                             LogPipe **outer_pipe_head, LogPipe **outer_pipe_tail)
{
  LogPipe *join_pipe = NULL;    /* the pipe where parallel branches are joined in a junction */
  LogPipe *midpoint_pipe = NULL;
  LogMultiplexer *fork_mpx = NULL;

  /* LC_XXX flags are currently only implemented for sequences, ensure that the grammar enforces this. */
  g_assert(node->flags == 0);

  LogExprNode *true_branch = node->children;
  LogExprNode *false_branch = node->children->next;
  LogExprNode *filter_expr = node->children->next->next;


  LogPipe *true_pipe_head, *true_pipe_tail;
  if (!cfg_tree_compile_node(self, true_branch, &true_pipe_head, &true_pipe_tail))
    goto error;

  LogPipe *false_pipe_head, *false_pipe_tail;
  if (!cfg_tree_compile_node(self, false_branch, &false_pipe_head, &false_pipe_tail))
    goto error;


  fork_mpx = cfg_tree_new_mpx(self, node, "mpx(conditional)");

  join_pipe = cfg_tree_new_pipe(self, node, "conditional-end");
  join_pipe->flags |= PIF_JUNCTION_END;


  if (filter_expr)
    {
      LogPipe *filter_pipe_head, *filter_pipe_tail;

      if (!cfg_tree_compile_node(self, filter_expr, &filter_pipe_head, &filter_pipe_tail))
        goto error;

      midpoint_pipe = cfg_tree_new_pipe(self, node, "conditional-midpoint");
      midpoint_pipe->flags |= PIF_CONDITIONAL_MIDPOINT;

      log_pipe_append(filter_pipe_tail, midpoint_pipe);
      log_pipe_append(midpoint_pipe, true_pipe_head);
      true_pipe_head = filter_pipe_head;
    }


  log_multiplexer_add_next_hop(fork_mpx, true_pipe_head);
  log_multiplexer_add_next_hop(fork_mpx, false_pipe_head);
  log_pipe_append(true_pipe_tail, join_pipe);
  log_pipe_append(false_pipe_tail, join_pipe);

  if (outer_pipe_head)
    *outer_pipe_head = &fork_mpx->super;
  if (outer_pipe_tail)
    *outer_pipe_tail = join_pipe;

  return TRUE;
error:

  /* we don't need to free anything, everything we allocated is recorded in
   * @self, thus will be freed whenever cfg_tree_free is called */

  return FALSE;
}

/*
 * cfg_tree_compile_node:
 *
 * This function takes care of compiling a LogExprNode.
 *
 */
gboolean
cfg_tree_compile_node(CfgTree *self, LogExprNode *node,
                      LogPipe **outer_pipe_head, LogPipe **outer_pipe_tail)
{
  gboolean result = FALSE;
  static gint indent = -1;
  gchar buf[128];

  indent++;
  msg_trace_printf("%-*sCompiling %s %s [%s] at [%s]",
                   indent * 2, "",
                   node->name ? : "#unnamed",
                   log_expr_node_get_layout_name(node->layout),
                   log_expr_node_get_content_name(node->content),
                   log_expr_node_format_location(node, buf, sizeof(buf)));

  switch (node->layout)
    {
    case ENL_SINGLE:
      result = cfg_tree_compile_single(self, node, outer_pipe_head, outer_pipe_tail);
      break;
    case ENL_REFERENCE:
      result = cfg_tree_compile_reference(self, node, outer_pipe_head, outer_pipe_tail);
      break;
    case ENL_SEQUENCE:
      result = cfg_tree_compile_sequence(self, node, outer_pipe_head, outer_pipe_tail);
      break;
    case ENL_JUNCTION:
      result = cfg_tree_compile_junction(self, node, outer_pipe_head, outer_pipe_tail);
      break;
    case ENL_CONDITIONAL:
      result = cfg_tree_compile_conditional(self, node, outer_pipe_head, outer_pipe_tail);
      break;
    default:
      g_assert_not_reached();
    }

  indent--;
  return result;
}

gboolean
cfg_tree_compile_rule(CfgTree *self, LogExprNode *rule)
{
  LogPipe *sub_pipe_head = NULL, *sub_pipe_tail = NULL;

  return cfg_tree_compile_node(self, rule, &sub_pipe_head, &sub_pipe_tail);
}

static gboolean
cfg_tree_objects_equal(gconstpointer v1, gconstpointer v2)
{
  LogExprNode *r1 = (LogExprNode *) v1;
  LogExprNode *r2 = (LogExprNode *) v2;

  if (r1->content != r2->content)
    return FALSE;

  /* we assume that only rules with a name are hashed */

  return strcmp(r1->name, r2->name) == 0;
}

static guint
cfg_tree_objects_hash(gconstpointer v)
{
  LogExprNode *r = (LogExprNode *) v;

  /* we assume that only rules with a name are hashed */
  return r->content + g_str_hash(r->name);
}

gboolean
cfg_tree_add_object(CfgTree *self, LogExprNode *rule)
{
  gboolean res = TRUE;

  if (rule->name && rule->content != ENC_PIPE)
    {
      /* only named rules can be stored as objects to be referenced later */

      /* check if already present */
      res = (g_hash_table_lookup(self->objects, rule) == NULL);

      /* key is the same as the object */
      g_hash_table_replace(self->objects, rule, rule);
    }
  else
    {
      /* unnamed rules are simply put in the rules array */
      g_ptr_array_add(self->rules, rule);
    }

  return res;
}

LogExprNode *
cfg_tree_get_object(CfgTree *self, gint content, const gchar *name)
{
  LogExprNode lookup_node;

  memset(&lookup_node, 0, sizeof(lookup_node));
  lookup_node.content = content;
  lookup_node.name = (gchar *) name;

  return g_hash_table_lookup(self->objects, &lookup_node);
}

GList *
cfg_tree_get_objects(CfgTree *self)
{
  return g_hash_table_get_values(self->objects);
}

gboolean
cfg_tree_add_template(CfgTree *self, LogTemplate *template_obj)
{
  gboolean res = (g_hash_table_lookup(self->templates, template_obj->name) == NULL);
  g_hash_table_replace(self->templates, template_obj->name, template_obj);
  return res;
}

LogTemplate *
cfg_tree_lookup_template(CfgTree *self, const gchar *name)
{
  if (name)
    return log_template_ref(g_hash_table_lookup(self->templates, name));
  return NULL;
}

LogTemplate *
cfg_tree_check_inline_template(CfgTree *self, const gchar *template_or_name, GError **error)
{
  LogTemplate *template = cfg_tree_lookup_template(self, template_or_name);

  if (template == NULL)
    {
      template = log_template_new(self->cfg, NULL);
      if (!log_template_compile(template, template_or_name, error))
        {
          log_template_unref(template);
          return NULL;
        }
      template->def_inline = TRUE;
    }
  return template;
}

gboolean
cfg_tree_compile(CfgTree *self)
{
  gint i;

  /* resolve references within the configuration */
  if (self->compiled)
    return TRUE;

  for (i = 0; i < self->rules->len; i++)
    {
      LogExprNode *rule = (LogExprNode *) g_ptr_array_index(self->rules, i);

      if ((rule->flags & LC_CATCHALL))
        {
          gpointer args[] = { self, rule };

          g_hash_table_foreach(self->objects, cfg_tree_add_all_sources, args);
          rule->flags &= ~LC_CATCHALL;
        }

      if (!cfg_tree_compile_rule(self, rule))
        {
          return FALSE;
        }
    }
  self->compiled = TRUE;
  return TRUE;
}

static gboolean
_verify_unique_persist_names_among_pipes(GHashTable *pipes_with_persis_name)
{
  GHashTable *pipe_persist_names = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL);
  gboolean result = TRUE;

  GList *pipes_with_persis_name_list = g_hash_table_get_values(pipes_with_persis_name);
  for (GList *pipe_list = pipes_with_persis_name_list; pipe_list != NULL; pipe_list = pipe_list->next)
    {
      LogPipe *current_pipe = (LogPipe *) pipe_list->data;
      const gchar *current_pipe_name = g_strdup(log_pipe_get_persist_name(current_pipe));

      if (current_pipe_name != NULL)
        {
          LogPipe *other_pipe = g_hash_table_lookup(pipe_persist_names, current_pipe_name);
          if (other_pipe)
            {
              msg_error("Automatic assignment of persist names failed, as "
                        "conflicting persist-names were found. Please override "
                        "the automatically assigned identifier using an "
                        "explicit perist-name() option or remove the duplicated "
                        "configuration elements",
                        evt_tag_str("persist_name", current_pipe_name),
                        log_pipe_location_tag(current_pipe),
                        log_pipe_location_tag(other_pipe));
              g_free((void *) current_pipe_name);
              result = FALSE;
              continue;
            }
          else
            {
              g_hash_table_replace(pipe_persist_names,
                                   (gpointer) current_pipe_name,
                                   current_pipe);
            }
        }
    }
  g_list_free(pipes_with_persis_name_list);

  g_hash_table_destroy(pipe_persist_names);

  return result;
}

gboolean
cfg_tree_start(CfgTree *self)
{
  gboolean fine = TRUE;
  gint i;

  g_assert(self->compiled);

  /*
   *   As there are pipes that are dynamically created during init, these
   *   pipes must be deinited before destroying the configuration, otherwise
   *   circular references will inhibit the free of the configuration
   *   structure.
   */
  cfg_tree_start_registering_pipes_with_persist_name(self);

  for (i = 0; i < self->initialized_pipes->len; i++)
    {
      LogPipe *pipe = g_ptr_array_index(self->initialized_pipes, i);

      if (!log_pipe_init(pipe))
        {
          msg_error("Error initializing message pipeline",
                    evt_tag_str("plugin_name", pipe->plugin_name ? pipe->plugin_name : "not a plugin"),
                    log_pipe_location_tag(pipe));
          fine = FALSE;
          break;
        }
    }

  if (fine)
    fine = _verify_unique_persist_names_among_pipes(self->pipes_with_persis_name);

  cfg_tree_stop_registering_pipes_with_persist_name(self);

  return fine;
}

gboolean
cfg_tree_stop(CfgTree *self)
{
  gboolean success = TRUE;
  gint i;

  for (i = 0; i < self->initialized_pipes->len; i++)
    {
      if (!log_pipe_deinit(g_ptr_array_index(self->initialized_pipes, i)))
        success = FALSE;
    }

  return success;
}

gboolean
cfg_tree_pre_config_init(CfgTree *self)
{
  gint i;

  g_assert(self->compiled);

  for (i = 0; i < self->initialized_pipes->len; i++)
    {
      LogPipe *pipe = g_ptr_array_index(self->initialized_pipes, i);

      if (!log_pipe_pre_config_init(pipe))
        {
          msg_error("Error executing pre_config_init hook",
                    evt_tag_str("plugin_name", pipe->plugin_name ? pipe->plugin_name : "not a plugin"),
                    log_pipe_location_tag(pipe));
          return FALSE;
        }
    }

  return TRUE;
}

gboolean
cfg_tree_post_config_init(CfgTree *self)
{
  gint i;

  for (i = 0; i < self->initialized_pipes->len; i++)
    {
      LogPipe *pipe = g_ptr_array_index(self->initialized_pipes, i);

      if (!log_pipe_post_config_init(pipe))
        {
          msg_error("Error executing post_config_init hook",
                    evt_tag_str("plugin_name", pipe->plugin_name ? pipe->plugin_name : "not a plugin"),
                    log_pipe_location_tag(pipe));
          return FALSE;
        }
    }

  return TRUE;
}

void
cfg_tree_init_instance(CfgTree *self, GlobalConfig *cfg)
{
  memset(self, 0, sizeof(*self));
  self->initialized_pipes = g_ptr_array_new();
  self->pipes_with_persis_name = NULL;
  self->objects = g_hash_table_new_full(cfg_tree_objects_hash, cfg_tree_objects_equal, NULL,
                                        (GDestroyNotify) log_expr_node_unref);
  self->templates = g_hash_table_new_full(g_str_hash, g_str_equal, NULL, (GDestroyNotify) log_template_unref);
  self->log_path_names = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL);
  self->rules = g_ptr_array_new();
  self->cfg = cfg;
}

void
cfg_tree_free_instance(CfgTree *self)
{
  g_ptr_array_foreach(self->initialized_pipes, (GFunc) log_pipe_unref, NULL);
  g_ptr_array_free(self->initialized_pipes, TRUE);

  g_ptr_array_foreach(self->rules, (GFunc) log_expr_node_unref, NULL);
  g_ptr_array_free(self->rules, TRUE);

  g_hash_table_destroy(self->objects);
  g_hash_table_destroy(self->templates);
  g_hash_table_destroy(self->log_path_names);

  self->cfg = NULL;
}