~xnox/ubuntu/vivid/upstart/fix-rotate-logs

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
/* upstart
 *
 * event.c - event queue and handling
 *
 * Copyright © 2010 Canonical Ltd.
 * Author: Scott James Remnant <scott@netsplit.com>.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2, as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif /* HAVE_CONFIG_H */


#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fnmatch.h>

#include <nih/macros.h>
#include <nih/alloc.h>
#include <nih/string.h>
#include <nih/tree.h>
#include <nih/logging.h>
#include <nih/error.h>

#include "environ.h"
#include "event.h"
#include "event_operator.h"
#include "blocked.h"
#include "errors.h"


/**
 * event_operator_new:
 * @parent: parent object for new operator,
 * @type: type of operator,
 * @name: name of event to match,
 * @env: NULL-terminated array of environment variables to match.
 *
 * Allocates and returns a new EventOperator structure with the @type given,
 * if @type is EVENT_MATCH then the operator will be used to match an event
 * with the given @name and @arguments using event_match().
 *
 * @env is optional, and may be NULL; if given it should be a NULL-terminated
 * array of environment variables in KEY=VALUE form.  @env will be referenced
 * by the new event.  After calling this function, you should never use
 * nih_free() to free @env and instead use nih_unref() or nih_discard() if
 * you no longer need to use it.
 *
 * If @parent is not NULL, it should be a pointer to another object which
 * will be used as a parent for the returned operator.  When all parents
 * of the returned operator are freed, the returned operator will also be
 * freed.
 *
 * Returns: newly allocated EventOperator structure, or NULL if
 * insufficient memory.
 **/
EventOperator *
event_operator_new (const void         *parent,
		    EventOperatorType   type,
		    const char         *name,
		    char              **env)
{
	EventOperator *oper;

	nih_assert ((type == EVENT_MATCH) || (name == NULL));
	nih_assert ((type == EVENT_MATCH) || (env == NULL));
	nih_assert ((type != EVENT_MATCH) || (name != NULL));

	oper = nih_new (parent, EventOperator);
	if (! oper)
		return NULL;

	nih_tree_init (&oper->node);

	oper->type = type;
	oper->value = FALSE;

	if (oper->type == EVENT_MATCH) {
		oper->name = nih_strdup (oper, name);
		if (! oper->name) {
			nih_free (oper);
			return NULL;
		}

		oper->env = env;
		if (oper->env)
			nih_ref (oper->env, oper);
	} else {
		oper->name = NULL;
		oper->env = NULL;
	}

	oper->event = NULL;

	nih_alloc_set_destructor (oper, event_operator_destroy);

	return oper;
}

/**
 * event_operator_copy:
 * @parent: parent object for new operator,
 * @old_oper: operator to copy.
 *
 * Allocates and returns a new EventOperator structure which is an identical
 * copy of @old_oper; including any matched state or events.
 *
 * If @old_oper is referencing an event, that status is also copied into the
 * newly returned operator; which will hold an additional block if
 * appropriate, on the event.
 *
 * If @old_oper has children, these will be copied as well, and will be
 * given their parent as their nih_alloc() parent.
 *
 * If @parent is not NULL, it should be a pointer to another object which
 * will be used as a parent for the returned operator.  When all parents
 * of the returned operator are freed, the returned operator will also be
 * freed.
 *
 * Returns: newly allocated EventOperator structure, or NULL if
 * insufficient memory.
 **/
EventOperator *
event_operator_copy (const void          *parent,
		     const EventOperator *old_oper)
{
	EventOperator *oper, *child;

	nih_assert (old_oper != NULL);

	oper = event_operator_new (parent, old_oper->type,
				   old_oper->name, NULL);
	if (! oper)
		return NULL;

	oper->value = old_oper->value;

	if (old_oper->env) {
		oper->env = nih_str_array_copy (oper, NULL, old_oper->env);
		if (! oper->env) {
			nih_free (oper);
			return NULL;
		}
	}

	if (old_oper->event) {
		oper->event = old_oper->event;
		event_block (oper->event);
	}

	if (old_oper->node.left) {
		child = event_operator_copy (
			oper, (EventOperator *)old_oper->node.left);
		if (! child) {
			nih_free (oper);
			return NULL;
		}

		nih_tree_add (&oper->node, &child->node, NIH_TREE_LEFT);
	}


	if (old_oper->node.right) {
		child = event_operator_copy (
			oper, (EventOperator *)old_oper->node.right);
		if (! child) {
			nih_free (oper);
			return NULL;
		}

		nih_tree_add (&oper->node, &child->node, NIH_TREE_RIGHT);
	}

	return oper;
}

/**
 * event_operator_destroy:
 * @oper: operator to be destroyed.
 *
 * Unblocks and unreferences the event referenced by @oper and unlinks it
 * from the event tree.
 *
 * Normally used or called from an nih_alloc() destructor so that the list
 * item is automatically removed from its containing list when freed.
 *
 * Returns: zero.
 **/
int
event_operator_destroy (EventOperator *oper)
{
	nih_assert (oper != NULL);

	if (oper->event)
		event_unblock (oper->event);

	nih_tree_destroy (&oper->node);

	return 0;
}


/**
 * event_operator_update:
 * @oper: operator to update.
 *
 * Updates the value of @oper to reflect the value of its child nodes
 * when combined with the particular operation this represents.
 *
 * This may only be called if the type of @oper is EVENT_OR or EVENT_AND.
 **/
void
event_operator_update (EventOperator *oper)
{
	EventOperator *left, *right;

	nih_assert (oper != NULL);
	nih_assert (oper->node.left != NULL);
	nih_assert (oper->node.right != NULL);

	left = (EventOperator *)oper->node.left;
	right = (EventOperator *)oper->node.right;

	switch (oper->type) {
	case EVENT_OR:
		oper->value = (left->value || right->value);
		break;
	case EVENT_AND:
		oper->value = (left->value && right->value);
		break;
	default:
		nih_assert_not_reached ();
	}
}

/**
 * event_operator_match:
 * @oper: operator to match against.
 * @event: event to match,
 * @env: NULL-terminated array of environment variables for expansion.
 *
 * Compares @oper against @event to see whether they are identical in name,
 * and whether @event contains a superset of the environment variables
 * given in @oper.
 *
 * @env is optional, and may be NULL; if given it should be a NULL-terminated
 * array of environment variables in KEY=VALUE form.
 *
 * Matching of environment is done first by position until the first variable
 * in @oper with a name specified is found, and subsequently by name.  Each
 * value is matched against the equivalent in @event as a glob, undergoing
 * expansion against @env first.
 *
 * This may only be called if the type of @oper is EVENT_MATCH.
 *
 * Returns: TRUE if the events match, FALSE otherwise.
 **/
int
event_operator_match (EventOperator *oper,
		      Event         *event,
		      char * const  *env)
{
	char * const *oenv;
	char * const *eenv;

	nih_assert (oper != NULL);
	nih_assert (oper->type == EVENT_MATCH);
	nih_assert (oper->node.left == NULL);
	nih_assert (oper->node.right == NULL);
	nih_assert (event != NULL);

	/* Names must match */
	if (strcmp (oper->name, event->name))
		return FALSE;

	/* Match operator environment variables against those from the event,
	 * starting both from the beginning.
	 */
	for (oenv = oper->env, eenv = event->env; oenv && *oenv;
	     oenv++, eenv++) {
		nih_local char *expoval = NULL;
		char           *oval, *eval;
		int             negate = FALSE;
		int             ret;

		oval = strstr (*oenv, "!=");
		if (! oval)
			oval = strchr (*oenv, '=');

		if (oval) {
			/* Hunt through the event environment to find the
			 * equivalent entry */
			eenv = environ_lookup (event->env, *oenv,
					       oval - *oenv);

			/* != means we negate the result (and skip the !) */
			if (*oval == '!') {
				negate = TRUE;
				oval++;
			}

			/* Value to match against follows the equals. */
			oval++;
		} else {
			/* Value to match against is the whole string. */
			oval = *oenv;
		}

		/* Make sure we haven't gone off the end of the event
		 * environment array; this catches both too many positional
		 * matches and no such variable.
		 */
		if (! (eenv && *eenv))
			return FALSE;

		/* Grab the value out by looking for the equals, we don't
		 * care about the name if we're positional and we've already
		 * matched it when not.
		 */
		eval = strchr (*eenv, '=');
		nih_assert (eval != NULL);
		eval++;

		/* Expand operator value against given environment before
		 * matching; silently discard errors, since otherwise we'd
		 * be excessively noisy on every event.
		 */
		while (! (expoval = environ_expand (NULL, oval, env))) {
			NihError *err;

			err = nih_error_get ();
			if (err->number != ENOMEM) {
				nih_free (err);
				return FALSE;
			}
			nih_free (err);
		}

		ret = fnmatch (expoval, eval, 0);

		if (negate ? (! ret) : ret)
			return FALSE;
	}

	return TRUE;
}


/**
 * event_operator_handle:
 * @root: operator tree to update,
 * @event: event to match against,
 * @env: NULL-terminated array of environment variables for expansion.
 *
 * Handles the emission of @event, matching it against EVENT_MATCH nodes in
 * the EventOperator tree rooted at @root, and updating the values of other
 * nodes to match.
 *
 * @env is optional, and may be NULL; if given it should be a NULL-terminated
 * array of environment variables in KEY=VALUE form and will be used to expand
 * EVENT_MATCH nodes before matching them,
 *
 * If @event is matched within this tree, it will be referenced and blocked
 * by the nodes that match it.  The blockage and references can be cleared
 * using event_operator_reset().
 *
 * Note that this returns to indicate whether a successful match was made;
 * you should also check the value of @root to make sure you react to this,
 * as that still may be FALSE.
 *
 * Returns: TRUE if @event matched an entry in the tree under @root, FALSE
 * otherwise.
 **/
int
event_operator_handle (EventOperator *root,
		       Event         *event,
		       char * const  *env)
{
	int ret = FALSE;

	nih_assert (root != NULL);
	nih_assert (event != NULL);

	/* A post-order traversal will give us the nodes in exactly the
	 * order we want.  We get a chance to update all of a node's children
	 * before we update the node itself.  Simply iterate the tree and
	 * update the nodes.
	 */
	NIH_TREE_FOREACH_POST (&root->node, iter) {
		EventOperator *oper = (EventOperator *)iter;

		switch (oper->type) {
		case EVENT_OR:
		case EVENT_AND:
			event_operator_update (oper);
			break;
		case EVENT_MATCH:
			if ((! oper->value)
			    && event_operator_match (oper, event, env)) {
				oper->value = TRUE;

				oper->event = event;
				event_block (oper->event);

				ret = TRUE;
			}
			break;
		default:
			nih_assert_not_reached ();
		}

	}

	return ret;
}


/**
 * event_operator_filter:
 * @data: not used,
 * @oper: EventOperator to check.
 *
 * Used when iterating the operator tree to filter out those operators and
 * their children for which the value is not TRUE.
 *
 * Returns: TRUE if operator should be ignored, FALSE otherwise.
 **/
static int
event_operator_filter (void          *data,
		       EventOperator *oper)
{
	nih_assert (oper != NULL);

	return oper->value != TRUE;
}

/**
 * event_operator_environment:
 * @root: operator tree to collect from,
 * @env: NULL-terminated array of environment variables to add to,
 * @parent: parent object for new array,
 * @len: length of @env,
 * @key: key of variable to contain event names.
 *
 * Collects environment from the portion of the EventOperator tree rooted at
 * @oper that are TRUE, ignoring the rest.
 *
 * Environment variables from each event (in tree order) will be added to
 * the NULL-terminated array at @env so that it contains the complete
 * environment of the operator.
 *
 * @len will be updated to contain the new array length and @env will
 * be updated to point to the new array pointer.
 *
 * Note that on failure, some of the entries may have been appended to
 * @env already.  This is normally not a problem, since entries will be
 * replaced in @env if this is repeated.
 *
 * If @key is not NULL, a key of that name will be set in @env (which must
 * not be NULL) containing a space-separated list of event names.
 *
 * If the array pointed to by @env is NULL, the array will be allocated and
 * if @parent is not NULL, it should be a pointer to another object which
 * will be used as a parent for the returned array.  When all parents of the
 * returned array are freed, the returned array will also be freed.
 *
 * When the array pointed to by @env is not NULL, @parent is ignored;
 * though it usual to pass a parent of @env for style reasons.
 *
 * Returns: pointer to new array on success, NULL on insufficient memory.
 **/
char **
event_operator_environment (EventOperator   *root,
			    char          ***env,
			    const void      *parent,
			    size_t          *len,
			    const char      *key)
{
	nih_local char *evlist = NULL;

	nih_assert (root != NULL);
	nih_assert (env != NULL);
	nih_assert (len != NULL);

	/* Initialise the event list variable with the name given. */
	if (key) {
		evlist = nih_sprintf (NULL, "%s=", key);
		if (! evlist)
			return NULL;
	}

	/* Always return an array, even if its zero length */
	if (! *env) {
		*env = nih_str_array_new (parent);
		if (! *env)
			return NULL;
	}

	/* Iterate the operator tree, filtering out nodes with a non-TRUE
	 * value and their children.  The rationale for this is that this
	 * then matches only the events that had an active role in starting
	 * the job, not the ones that were also blocked, but the other half
	 * of their logic wasn't present.
	 */
	NIH_TREE_FOREACH_FULL (&root->node, iter,
			       (NihTreeFilter)event_operator_filter, NULL) {
		EventOperator *oper = (EventOperator *)iter;

		if (oper->type != EVENT_MATCH)
			continue;

		nih_assert (oper->event != NULL);

		/* Add environment from the event */
		if (! environ_append (env, parent, len, TRUE, oper->event->env))
			return NULL;

		/* Append the name of the event to the string we're building */
		if (evlist) {
			if (evlist[strlen (evlist) - 1] != '=') {
				if (! nih_strcat_sprintf (&evlist, NULL, " %s",
							  oper->event->name))
					return NULL;
			} else {
				if (! nih_strcat (&evlist, NULL,
						  oper->event->name))
					return NULL;
			}
		}
	}

	/* Append the event list to the environment */
	if (evlist)
		if (! environ_add (env, parent, len, TRUE, evlist))
			return NULL;

	return *env;
}

/**
 * event_operator_fds:
 * @root: operator tree to update,
 * @parent: parent object for new array,
 * @fds: output location for array of ints
 * @num_fds: number of elements in @fds,
 * @env: NULL-terminated array of environment variables to add to,
 * @len: length of @env,
 * @key: key of variable to contain event names.
 *
 * Iterate over tree rooted at @root adding all file descriptor values found
 * to the dynamically allocated @fds array. In addition, all file
 * descriptors found are also added to @env will contain a new entry with key @key
 * whose value is a space-separated list of file descriptor numbers.
 *
 * Returns: 1 on success, NULL on failure.
 **/
int *
event_operator_fds (EventOperator  *root,
		    const void     *parent,
		    int           **fds,
		    size_t         *num_fds,
		    char         ***env,
		    size_t         *len,
		    const char     *key)
{
	nih_local char *evlist = NULL;

	nih_assert (root != NULL);
	nih_assert (fds != NULL);
	nih_assert (num_fds != NULL);
	nih_assert (env != NULL);
	nih_assert (len != NULL);
	nih_assert (key != NULL);

	/* Initialise the event list variable with the name given. */
	evlist = nih_sprintf (NULL, "%s=", key);
	if (! evlist)
		return NULL;

	*num_fds = 0;
	NIH_TREE_FOREACH_FULL (&root->node, iter,
			       (NihTreeFilter)event_operator_filter, NULL) {
		EventOperator *oper = (EventOperator *)iter;

		if (oper->type != EVENT_MATCH)
			continue;

		nih_assert (oper->event != NULL);

		if (oper->event->fd >= 0) {
			*fds = nih_realloc (*fds, parent, sizeof (int) * (*num_fds + 1));
			if (! *fds)
				return NULL;

			(*fds)[(*num_fds)++] = oper->event->fd;

			if (evlist[strlen (evlist) - 1] != '=') {
				if (! nih_strcat_sprintf (&evlist, NULL, " %d",
							  oper->event->fd))
					return NULL;
			} else {
				if (! nih_strcat_sprintf (&evlist, NULL, "%d",
							  oper->event->fd))
					return NULL;
			}
		}
	}

	if (*num_fds)
		if (! environ_add (env, parent, len, TRUE, evlist))
			return NULL;

	return (void *)1;
}

/**
 * event_operator_events:
 * @root: operator tree to collect from,
 * @parent: parent object for blocked structures,
 * @list: list to add events to.
 *
 * Collects events from the portion of the EventOperator tree rooted at @root
 * that are TRUE, ignoring the rest.
 *
 * Each event is blocked and a Blocked structure will be appended to @list
 * for it.
 *
 * If @parent is not NULL, it should be a pointer to another object which
 * will be used as a parent for the returned structures.  When all parents
 * of a returned structure are freed, the returned structure will also be
 * freed.
 **/
void
event_operator_events (EventOperator *root,
		       const void    *parent,
		       NihList       *list)
{
	nih_assert (root != NULL);
	nih_assert (list != NULL);

	/* Iterate the operator tree, filtering out nodes with a non-TRUE
	 * value and their children.  The rationale for this is that this
	 * then matches only the events that had an active role in starting
	 * the job, not the ones that were also blocked, but the other half
	 * of their logic wasn't present.
	 */
	NIH_TREE_FOREACH_FULL (&root->node, iter,
			       (NihTreeFilter)event_operator_filter, NULL) {
		EventOperator *oper = (EventOperator *)iter;
		Blocked       *blocked;

		if (oper->type != EVENT_MATCH)
			continue;

		nih_assert (oper->event != NULL);

		blocked = NIH_MUST (blocked_new (parent, BLOCKED_EVENT,
						 oper->event));
		nih_list_add (list, &blocked->entry);

		event_block (blocked->event);
	}
}


/**
 * event_operator_reset:
 * @root: operator tree to update.
 *
 * Resets the EventOperator tree rooted at @oper, unblocking and
 * unreferencing any events that were matched by the tree and changing
 * the values of other operators to match.
 **/
void
event_operator_reset (EventOperator *root)
{
	nih_assert (root != NULL);

	/* A post-order iteration means we visit children first, perfect! */
	NIH_TREE_FOREACH_POST (&root->node, iter) {
		EventOperator *oper = (EventOperator *)iter;

		switch (oper->type) {
		case EVENT_OR:
		case EVENT_AND:
			event_operator_update (oper);
			break;
		case EVENT_MATCH:
			oper->value = FALSE;

			if (oper->event) {
				event_unblock (oper->event);
				oper->event = NULL;
			}
			break;
		default:
			nih_assert_not_reached ();
		}
	}
}

/**
 * event_operator_collapse:
 *
 * @condition: start on/stop on condition.
 *
 * Collapsed condition will be fully bracketed. Note that as such it may
 * not be lexicographically identical to the original expression that
 * resulted in @condition, but it will be logically identical.
 *
 * The condition is reconstructed from the EventOperator tree by using
 * a post-order traversal (since this allows the tree to be traversed
 * bottom-to-top). Leaf nodes (EVENT_MATCH) are ignored when visited,
 * allowing non-leaf nodes (EVENT_AND and EVENT_OR) to simply grab the
 * value of their children, construct a bracketed expression and add it
 * to a stack. If a child is a leaf node, the value can be read
 * directly. If a child is a non-leaf node, the value is obtained by
 * popping the stack before adding the new value back onto the stack.
 * When finally the root node is visited, the final expression can be
 * removed from the stack and returned. A single-node tree (comprising a
 * lone EVENT_MATCH at the root) is special-cased.
 *
 * Returns: newly-allocated flattened string representing @condition
 * on success, or NULL on error.
 **/
char *
event_operator_collapse (EventOperator *condition)
{
	nih_local NihList       *stack = NULL;
	NihListEntry            *latest = NULL;
	NihTree                 *root;

	nih_assert (condition);

	root = &condition->node;

	stack = NIH_MUST (nih_list_new (NULL));

	NIH_TREE_FOREACH_POST (root, iter) {
		EventOperator   *oper = (EventOperator *)iter;
		EventOperator   *left;
		EventOperator   *right;
		NihListEntry    *expr;
		NihTree         *tree;
		nih_local char  *left_expr = NULL;
		nih_local char  *right_expr = NULL;

		tree = &oper->node;

		left = (EventOperator *)tree->left;
		right = (EventOperator *)tree->right;

		if (oper->type == EVENT_MATCH) {
			/* Entire expression comprises a single event,
			 * so push it and leave.
			 */
			if (tree == root) {
				nih_local char *env = NULL;

				if (oper->env)
					env = NIH_MUST (state_collapse_env ((const char **)oper->env));

				expr = NIH_MUST (nih_list_entry_new (stack));
				expr->str = NIH_MUST (nih_sprintf (expr, "%s%s%s",
							oper->name,
							env ? " " : "",
							env ? env : ""));
				nih_list_add_after (stack, &expr->entry);
				break;
			} else {
				/* We build the expression from visiting the logical
				 * operators (and their children) only.
				 */
				continue;
			}
		}

		/* oper cannot now be a leaf node, so must have children */
		nih_assert (left);
		nih_assert (right);

		expr = NIH_MUST (nih_list_entry_new (stack));

		/* If a child is an EVENT_MATCH, expand its event
		 * details and push onto the stack.
		 * If a child is not an EVENT_MATCH, to obtains it
		 * value, pop the stack.
		 *
		 * Having obtained the child values, construct a new
		 * bracketed expression and push onto the stack.
		 *
		 * Note that we must consider the right child first.
		 * This is because since the tree is traversed
		 * left-child first, any value pushed onto the stack by
		 * a right child is at the top so must be removed before
		 * any left child value. Failure to do this results in
		 * tree reflection which although logically equivalent
		 * to the original could confuse as the resultant
		 * expression will look rather different.
		 */
		if (right->type != EVENT_MATCH) {
			nih_assert (! NIH_LIST_EMPTY (stack));

			latest = (NihListEntry *)nih_list_remove (stack->next);
			right_expr = NIH_MUST (nih_strdup (NULL, latest->str));
		} else {
			nih_local char *env = NULL;

			if (right->env)
				env = NIH_MUST (state_collapse_env ((const char **)right->env));

			right_expr = NIH_MUST (nih_sprintf (NULL, "%s%s%s",
						right->name,
						env ? " " : "",
						env ? env : ""));
		}

		if (left->type != EVENT_MATCH) {
			nih_assert (! NIH_LIST_EMPTY (stack));

			latest = (NihListEntry *)nih_list_remove (stack->next);
			left_expr = NIH_MUST (nih_strdup (NULL, latest->str));
		} else {
			nih_local char *env = NULL;

			if (left->env)
				env = NIH_MUST (state_collapse_env ((const char **)left->env));

			left_expr = NIH_MUST (nih_sprintf (NULL, "%s%s%s",
						left->name,
						env ? " " : "",
						env ? env : ""));
		}

		expr->str = NIH_MUST (nih_sprintf (expr, "(%s %s %s)",
					left_expr,
					oper->type == EVENT_OR ? "or" : "and",
					right_expr));

		nih_list_add_after (stack, &expr->entry);
	}

	nih_assert (! NIH_LIST_EMPTY (stack));

	latest = (NihListEntry *)nih_list_remove (stack->next);

	nih_assert (NIH_LIST_EMPTY (stack));

	return NIH_MUST (nih_strdup (NULL, latest->str));
}

/**
 * event_operator_type_enum_to_str:
 *
 * @type: EventOperatorType.
 *
 * Convert EventOperatorType to a string representation.
 *
 * Returns: string representation of @type, or NULL if not known.
 **/
const char *
event_operator_type_enum_to_str (EventOperatorType type)
{
	state_enum_to_str (EVENT_OR, type);
	state_enum_to_str (EVENT_AND, type);
	state_enum_to_str (EVENT_MATCH, type);

	return NULL;
}

/**
 * event_operator_type_str_to_enum:
 *
 * @type: string EventOperatorType value.
 *
 * Convert @expect back into an enum value.
 *
 * Returns: EventOperatorType representing @type, or -1 if not known.
 **/
EventOperatorType
event_operator_type_str_to_enum (const char *type)
{
	nih_assert (type);

	state_str_to_enum (EVENT_OR, type);
	state_str_to_enum (EVENT_AND, type);
	state_str_to_enum (EVENT_MATCH, type);

	return -1;
}

/**
 * event_operator_serialise:
 * @oper: EventOperator to serialise.
 *
 * Convert @oper into a JSON representation for serialisation.
 * Caller must free returned value using json_object_put().
 *
 * Returns: JSON-serialised EventOperator object, or NULL on error.
 **/
json_object *
event_operator_serialise (const EventOperator *oper)
{
	json_object  *json;
	int           event_index;

	nih_assert (oper);

	json = json_object_new_object ();
	if (! json)
		return NULL;

	if (! state_set_json_enum_var (json,
				event_operator_type_enum_to_str,
				"type", oper->type))
		goto error;

	if (! state_set_json_int_var_from_obj (json, oper, value))
		goto error;

	if (oper->name) {
		if (! state_set_json_string_var_from_obj (json, oper, name))
			goto error;
	}

	if (oper->env) {
		if (! state_set_json_str_array_from_obj (json, oper, env))
			goto error;
	}

	if (oper->event) {
		event_index = event_to_index (oper->event);
		if (event_index < 0)
			goto error;

		if (! state_set_json_int_var (json, "event", event_index))
			goto error;
	}

	return json;

error:
	json_object_put (json);
	return NULL;

}

/**
 * event_operator_serialise_all:
 *
 * @root: operator tree to serialise,
 *
 * Convert EventOperator tree to JSON representation.
 *
 * Returns: JSON object containing array of EventOperator nodes in post-order,
 * or NULL on error.
 */
json_object *
event_operator_serialise_all (EventOperator *root)
{
	json_object *json;
	json_object *json_node;

	nih_assert (root);

	json = json_object_new_array ();
	if (! json)
		return NULL;

	NIH_TREE_FOREACH_POST (&root->node, iter) {
		EventOperator *oper = (EventOperator *)iter;

		json_node = event_operator_serialise (oper);
		if (! json_node)
			goto error;

		if (json_object_array_add (json, json_node) < 0)
			goto error;
	}

	return json;

error:
	json_object_put (json);
	return NULL;
}

/**
 * event_operator_deserialise:
 * @parent: parent,
 * @json: JSON-serialised EventOperator object to deserialise.
 *
 * Create EventOperator from provided JSON.
 *
 * Returns: EventOperator object, or NULL on error.
 **/
EventOperator *
event_operator_deserialise (void *parent, json_object *json)
{
	EventOperator      *oper = NULL;
	EventOperatorType   type = -1;
	nih_local char     *name = NULL;
	nih_local char    **env = NULL;

	nih_assert (json);

	if (! state_check_json_type (json, object))
		goto error;

	if (json_object_object_get_ex (json, "name", NULL)) {
		if (! state_get_json_string_var_strict (json, "name", NULL, name))
			goto error;
	}

	if (! state_get_json_enum_var (json,
				event_operator_type_str_to_enum,
				"type", type))
		goto error;

	if (json_object_object_get_ex (json, "env", NULL)) {
		json_object  *json_env;
		if (! state_get_json_var_full (json, "env", array, json_env))
			goto error;

		/* XXX: note that we have to treat the environment array
		 * as a plain string array (rather than an environ
		 * array) at this point since the values are not
		 * expanded (do not necessarily contain '='), and hence
		 * would be discarded by the environ-handling routines.
		 */
		if (! state_deserialise_str_array (NULL, json_env, &env))
			goto error;
	}

	oper = event_operator_new (parent, type, name, env);
	if (! oper)
		goto error;

	if (! state_get_json_int_var_to_obj (json, oper, value))
		goto error;

	if (json_object_object_get_ex (json, "event", NULL)) {
		int event_index;

		if (! state_get_json_int_var (json, "event", event_index))
			goto error;

		oper->event = event_from_index (event_index);
		if (! oper->event)
			goto error;
	}

	return oper;

error:
	if (oper)
		nih_free (oper);

	return NULL;
}

/**
 * event_operator_deserialise_all:
 *
 * @parent: parent,
 * @json: root of JSON-serialised state.
 *
 * Convert EventOperator tree to JSON representation.
 *
 * Returns: EventOperator tree root node on success, or NULL on error.
 */
EventOperator *
event_operator_deserialise_all (void *parent, json_object *json)
{
	EventOperator      *oper = NULL;
	EventOperator      *left_oper = NULL;
	EventOperator      *right_oper = NULL;
	nih_local NihList  *stack = NULL;
	NihListEntry       *item;

	nih_assert (json);

	stack = NIH_MUST (nih_list_new (NULL));

	if (! state_check_json_type (json, array))
		goto error;

	for (int i = 0; i < json_object_array_length (json); i++) {
		json_object        *json_event_operator;
		nih_local NihList  *left = NULL;
		nih_local NihList  *right = NULL;

		json_event_operator = json_object_array_get_idx (json, i);
		if (! json_event_operator)
			goto error;

		if (! state_check_json_type (json_event_operator, object))
			goto error;

		oper = event_operator_deserialise (parent, json_event_operator);
		if (! oper)
			goto error;

		item = nih_list_entry_new (stack);
		if (! item)
			goto error;

		switch (oper->type) {
		case EVENT_AND:
		case EVENT_OR:
			left = NIH_MUST (nih_list_new (NULL));
			right = NIH_MUST (nih_list_new (NULL));

			/* pop the top two stack elements */
			nih_assert (! NIH_LIST_EMPTY (stack));
			right = nih_list_add (right, stack->next);

			nih_assert (! NIH_LIST_EMPTY (stack));
			left = nih_list_add (left, stack->next);

			left_oper = (EventOperator *)((NihListEntry *)left)->data;
			right_oper = (EventOperator *)((NihListEntry *)right)->data;

			nih_assert (left_oper);
			nih_assert (right_oper);

			/* Attach them as children of the new operator */
			nih_tree_add (&oper->node, &left_oper->node, NIH_TREE_LEFT);
			nih_tree_add (&oper->node, &right_oper->node, NIH_TREE_RIGHT);

			/* FALL THROUGH:
			 *
			 * This will re-add the operator to the stack.
			 */

		case EVENT_MATCH:
			item->data = oper;
			nih_list_add_after (stack, &item->entry);
			break;
		default:
			nih_assert_not_reached ();
		}
	}

	nih_assert (! NIH_LIST_EMPTY (stack));

	oper = ((NihListEntry *)stack->next)->data;

	nih_list_remove (stack->next);
	nih_assert (NIH_LIST_EMPTY (stack));

	return oper;

error:
	if (oper)
		nih_free (oper);

	return NULL;
}