summaryrefslogtreecommitdiffstats
path: root/plugins/sudoers/cvtsudoers.c
blob: 0221314b97f2ab75902729911b65d170f582500f (plain)
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
/*
 * Copyright (c) 2018 Todd C. Miller <Todd.Miller@sudo.ws>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/*
 * This is an open source non-commercial project. Dear PVS-Studio, please check it.
 * PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
 */

/*
 * Convert from the sudoers file format to LDIF or JSON format.
 */

#include <config.h>

#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#ifdef HAVE_STRING_H
# include <string.h>
#endif /* HAVE_STRING_H */
#ifdef HAVE_STRINGS_H
# include <strings.h>
#endif /* HAVE_STRINGS_H */
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <pwd.h>
#include <unistd.h>

#include "sudoers.h"
#include "sudoers_version.h"
#include "sudo_conf.h"
#include "sudo_lbuf.h"
#include "redblack.h"
#include "cvtsudoers.h"
#include <gram.h>

#ifdef HAVE_GETOPT_LONG
# include <getopt.h>
# else
# include "compat/getopt.h"
#endif /* HAVE_GETOPT_LONG */

/*
 * Globals
 */
struct cvtsudoers_filter *filters;
struct sudo_user sudo_user;
struct passwd *list_pw;
static const char short_opts[] =  "b:c:d:ef:hi:I:m:Mo:O:pP:s:V";
static struct option long_opts[] = {
    { "base",		required_argument,	NULL,	'b' },
    { "config",		required_argument,	NULL,	'c' },
    { "defaults",	required_argument,	NULL,	'd' },
    { "expand-aliases",	no_argument,		NULL,	'e' },
    { "output-format",	required_argument,	NULL,	'f' },
    { "help",		no_argument,		NULL,	'h' },
    { "input-format",	required_argument,	NULL,	'i' },
    { "increment",	required_argument,	NULL,	'I' },
    { "match",		required_argument,	NULL,	'm' },
    { "match-local",	no_argument,		NULL,	'M' },
    { "prune-matches",	no_argument,		NULL,	'p' },
    { "padding",	required_argument,	NULL,	'P' },
    { "order-start",	required_argument,	NULL,	'O' },
    { "output",		required_argument,	NULL,	'o' },
    { "suppress",	required_argument,	NULL,	's' },
    { "version",	no_argument,		NULL,	'V' },
    { NULL,		no_argument,		NULL,	'\0' },
};

__dso_public int main(int argc, char *argv[]);
static void help(void) __attribute__((__noreturn__));
static void usage(int);
static bool convert_sudoers_sudoers(struct sudoers_parse_tree *parse_tree, const char *output_file, struct cvtsudoers_config *conf);
static bool parse_sudoers(const char *input_file, struct cvtsudoers_config *conf);
static bool parse_ldif(struct sudoers_parse_tree *parse_tree, const char *input_file, struct cvtsudoers_config *conf);
static bool cvtsudoers_parse_filter(char *expression);
static struct cvtsudoers_config *cvtsudoers_conf_read(const char *conf_file);
static void cvtsudoers_conf_free(struct cvtsudoers_config *conf);
static int cvtsudoers_parse_defaults(char *expression);
static int cvtsudoers_parse_suppression(char *expression);
static void filter_userspecs(struct sudoers_parse_tree *parse_tree, struct cvtsudoers_config *conf);
static void filter_defaults(struct sudoers_parse_tree *parse_tree, struct cvtsudoers_config *conf);
static void alias_remove_unused(struct sudoers_parse_tree *parse_tree);
static void alias_prune(struct sudoers_parse_tree *parse_tree, struct cvtsudoers_config *conf);

int
main(int argc, char *argv[])
{
    int ch, exitcode = EXIT_FAILURE;
    enum sudoers_formats output_format = format_ldif;
    enum sudoers_formats input_format = format_sudoers;
    struct cvtsudoers_config *conf = NULL;
    bool match_local = false;
    const char *input_file = "-";
    const char *output_file = "-";
    const char *conf_file = _PATH_CVTSUDOERS_CONF;
    const char *errstr;
    debug_decl(main, SUDOERS_DEBUG_MAIN)

#if defined(SUDO_DEVEL) && defined(__OpenBSD__)
    {
	extern char *malloc_options;
	malloc_options = "S";
    }
#endif

    initprogname(argc > 0 ? argv[0] : "cvtsudoers");
    if (!sudoers_initlocale(setlocale(LC_ALL, ""), def_sudoers_locale))
	sudo_fatalx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
    sudo_warn_set_locale_func(sudoers_warn_setlocale);
    bindtextdomain("sudoers", LOCALEDIR);
    textdomain("sudoers");

    /* Read debug and plugin sections of sudo.conf. */
    if (sudo_conf_read(NULL, SUDO_CONF_DEBUG|SUDO_CONF_PLUGINS) == -1)
	goto done;

    /* Initialize the debug subsystem. */
    if (!sudoers_debug_register(getprogname(), sudo_conf_debug_files(getprogname())))
	goto done;

    /* Check for --config option first (no getopt warnings). */
    opterr = 0;
    while ((ch = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1) {
	switch (ch) {
	case 'c':
	    conf_file = optarg;
	    break;
	}
    }

    /* Read conf file. */
    conf = cvtsudoers_conf_read(conf_file);

    /*
     * Reset getopt and handle the rest of the arguments.
     */
    opterr = 1;
    optind = 1;
#ifdef HAVE_OPTRESET
    optreset = 1;
#endif
    while ((ch = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1) {
	switch (ch) {
	case 'b':
	    free(conf->sudoers_base);
	    conf->sudoers_base = strdup(optarg);
	    if (conf->sudoers_base == NULL) {
		sudo_fatalx(U_("%s: %s"), __func__,
		    U_("unable to allocate memory"));
	    }
	    break;
	case 'c':
	    /* handled above */
	    break;
	case 'd':
	    conf->defstr = optarg;
	    break;
	case 'e':
	    conf->expand_aliases = true;
	    break;
	case 'f':
	    free(conf->output_format);
	    conf->output_format = strdup(optarg);
	    if (conf->output_format == NULL) {
		sudo_fatalx(U_("%s: %s"), __func__,
		    U_("unable to allocate memory"));
	    }
	    break;
	case 'h':
	    help();
	    break;
	case 'i':
	    free(conf->input_format);
	    conf->input_format = strdup(optarg);
	    if (conf->input_format == NULL) {
		sudo_fatalx(U_("%s: %s"), __func__,
		    U_("unable to allocate memory"));
	    }
	    break;
	case 'I':
	    conf->order_increment = sudo_strtonum(optarg, 1, UINT_MAX, &errstr);
	    if (errstr != NULL) {
		sudo_warnx(U_("order increment: %s: %s"), optarg, U_(errstr));
		usage(1);
	    }
	    break;
	case 'm':
	    conf->filter = optarg;
	    break;
	case 'M':
	    match_local = true;
	    break;
	case 'o':
	    output_file = optarg;
	    break;
	case 'O':
	    conf->sudo_order = sudo_strtonum(optarg, 0, UINT_MAX, &errstr);
	    if (errstr != NULL) {
		sudo_warnx(U_("starting order: %s: %s"), optarg, U_(errstr));
		usage(1);
	    }
	    break;
	case 'p':
	    conf->prune_matches = true;
	    break;
	case 'P':
	    conf->order_padding = sudo_strtonum(optarg, 1, UINT_MAX, &errstr);
	    if (errstr != NULL ) {
		sudo_warnx(U_("order padding: %s: %s"), optarg, U_(errstr));
		usage(1);
	    }
	    break;
	case 's':
	    conf->supstr = optarg;
	    break;
	case 'V':
	    (void) printf(_("%s version %s\n"), getprogname(),
		PACKAGE_VERSION);
	    (void) printf(_("%s grammar version %d\n"), getprogname(),
		SUDOERS_GRAMMAR_VERSION);
	    exitcode = EXIT_SUCCESS;
	    goto done;
	default:
	    usage(1);
	}
    }
    argc -= optind;
    argv += optind;

    if (conf->input_format != NULL) {
	if (strcasecmp(conf->input_format, "ldif") == 0) {
	    input_format = format_ldif;
	} else if (strcasecmp(conf->input_format, "sudoers") == 0) {
	    input_format = format_sudoers;
	} else {
	    sudo_warnx(U_("unsupported input format %s"), conf->input_format);
	    usage(1);
	}
    }
    if (conf->output_format != NULL) {
	if (strcasecmp(conf->output_format, "json") == 0) {
	    output_format = format_json;
	    conf->store_options = true;
	} else if (strcasecmp(conf->output_format, "ldif") == 0) {
	    output_format = format_ldif;
	    conf->store_options = true;
	} else if (strcasecmp(conf->output_format, "sudoers") == 0) {
	    output_format = format_sudoers;
	    conf->store_options = false;
	} else {
	    sudo_warnx(U_("unsupported output format %s"), conf->output_format);
	    usage(1);
	}
    }
    if (conf->filter != NULL) {
	/* We always expand aliases when filtering (may change in future). */
	if (!cvtsudoers_parse_filter(conf->filter))
	    usage(1);
    }
    if (conf->defstr != NULL) {
	conf->defaults = cvtsudoers_parse_defaults(conf->defstr);
	if (conf->defaults == -1)
	    usage(1);
    }
    if (conf->supstr != NULL) {
	conf->suppress = cvtsudoers_parse_suppression(conf->supstr);
	if (conf->suppress == -1)
	    usage(1);
    }

    /* Apply padding to sudo_order if present. */
    if (conf->sudo_order != 0 && conf->order_padding != 0) {
	unsigned int multiplier = 1;

	do {
	    multiplier *= 10;
	} while (--conf->order_padding != 0);
	conf->sudo_order *= multiplier;
	conf->order_max = conf->sudo_order + (multiplier - 1);
	conf->order_padding = multiplier;
    }

    /* If no base DN specified, check SUDOERS_BASE. */
    if (conf->sudoers_base == NULL) {
	conf->sudoers_base = getenv("SUDOERS_BASE");
	if (conf->sudoers_base != NULL && *conf->sudoers_base != '\0') {
	    if ((conf->sudoers_base = strdup(conf->sudoers_base)) == NULL) {
		sudo_fatalx(U_("%s: %s"), __func__,
		    U_("unable to allocate memory"));
	    }
	}
    }

    /* Input file (defaults to stdin). */
    if (argc > 0) {
	if (argc > 1)
	    usage(1);
	input_file = argv[0];
    }

    if (strcmp(input_file, "-") != 0) {
	if (strcmp(input_file, output_file) == 0) {
	    sudo_fatalx(U_("%s: input and output files must be different"),
		input_file);
	}
    }

    /* Set pwutil backend to use the filter data. */
    if (conf->filter != NULL && !match_local) {
	sudo_pwutil_set_backend(cvtsudoers_make_pwitem, cvtsudoers_make_gritem,
	    cvtsudoers_make_gidlist_item, cvtsudoers_make_grlist_item);
    }

    /* We may need the hostname to resolve %h escapes in include files. */
    get_hostname();

    /* Setup defaults data structures. */
    if (!init_defaults())
	sudo_fatalx(U_("unable to initialize sudoers default values"));

    switch (input_format) {
    case format_ldif:
	if (!parse_ldif(&parsed_policy, input_file, conf))
	    goto done;
	break;
    case format_sudoers:
	if (!parse_sudoers(input_file, conf))
	    goto done;
	break;
    default:
	sudo_fatalx("error: unhandled input %d", input_format);
    }

    /* Apply filters. */
    filter_userspecs(&parsed_policy, conf);
    filter_defaults(&parsed_policy, conf);
    if (filters != NULL) {
	alias_remove_unused(&parsed_policy);
	if (conf->prune_matches && conf->expand_aliases)
	    alias_prune(&parsed_policy, conf);
    }

    switch (output_format) {
    case format_json:
	exitcode = !convert_sudoers_json(&parsed_policy, output_file, conf);
	break;
    case format_ldif:
	exitcode = !convert_sudoers_ldif(&parsed_policy, output_file, conf);
	break;
    case format_sudoers:
	exitcode = !convert_sudoers_sudoers(&parsed_policy, output_file, conf);
	break;
    default:
	sudo_fatalx("error: unhandled output format %d", output_format);
    }

done:
    cvtsudoers_conf_free(conf);
    sudo_debug_exit_int(__func__, __FILE__, __LINE__, sudo_debug_subsys, exitcode);
    return exitcode;
}

/*
 * cvtsudoers configuration data.
 */
static struct cvtsudoers_config cvtsudoers_config = INITIAL_CONFIG;
static struct cvtsudoers_conf_table cvtsudoers_conf_vars[] = {
    { "order_start", CONF_UINT, &cvtsudoers_config.sudo_order },
    { "order_increment", CONF_UINT, &cvtsudoers_config.order_increment },
    { "order_padding", CONF_UINT, &cvtsudoers_config.order_padding },
    { "sudoers_base", CONF_STR, &cvtsudoers_config.sudoers_base },
    { "input_format", CONF_STR, &cvtsudoers_config.input_format },
    { "output_format", CONF_STR, &cvtsudoers_config.output_format },
    { "match", CONF_STR, &cvtsudoers_config.filter },
    { "defaults", CONF_STR, &cvtsudoers_config.defstr },
    { "suppress", CONF_STR, &cvtsudoers_config.supstr },
    { "expand_aliases", CONF_BOOL, &cvtsudoers_config.expand_aliases },
    { "prune_matches", CONF_BOOL, &cvtsudoers_config.prune_matches }
};

/*
 * Look up keyword in config table.
 * Returns true if found, else false.
 */
static bool
cvtsudoers_parse_keyword(const char *conf_file, const char *keyword,
    const char *value, struct cvtsudoers_conf_table *table)
{
    struct cvtsudoers_conf_table *cur;
    const char *errstr;
    debug_decl(sudo_ldap_parse_keyword, SUDOERS_DEBUG_UTIL)

    /* Look up keyword in config tables */
    for (cur = table; cur->conf_str != NULL; cur++) {
	if (strcasecmp(keyword, cur->conf_str) == 0) {
	    switch (cur->type) {
	    case CONF_BOOL:
		*(bool *)(cur->valp) = sudo_strtobool(value) == true;
		break;
	    case CONF_UINT:
		{
		    unsigned int uval = 
			strtonum(value, 0, UINT_MAX, &errstr);
		    if (errstr != NULL) {
			sudo_warnx(U_("%s: %s: %s: %s"),
			    conf_file, keyword, value, U_(errstr));
			continue;
		    }
		    *(unsigned int *)(cur->valp) = uval;
		}
		break;
	    case CONF_STR:
		{
		    char *cp = strdup(value);
		    if (cp == NULL) {
			sudo_fatalx(U_("%s: %s"), __func__,
			    U_("unable to allocate memory"));
		    }
		    free(*(char **)(cur->valp));
		    *(char **)(cur->valp) = cp;
		    break;
		}
	    }
	    debug_return_bool(true);
	}
    }
    debug_return_bool(false);
}

static struct cvtsudoers_config *
cvtsudoers_conf_read(const char *conf_file)
{
    char *line = NULL;
    size_t linesize = 0;
    FILE *fp;
    debug_decl(cvtsudoers_conf_read, SUDOERS_DEBUG_UTIL)

    if ((fp = fopen(conf_file, "r")) == NULL)
	debug_return_ptr(&cvtsudoers_config);

    while (sudo_parseln(&line, &linesize, NULL, fp, 0) != -1) {
	char *cp, *keyword, *value;

	if (*line == '\0')
	    continue;		/* skip empty line */

	/* Parse keyword = value */
	keyword = line;
	if ((cp = strchr(line, '=')) == NULL)
	    continue;
	value = cp-- + 1;

	/* Trim whitespace after keyword. */
	while (cp != line && isblank((unsigned char)cp[-1]))
	    cp--;
	*cp = '\0';

	/* Trim whitespace before value. */
	while (isblank((unsigned char)*value))
	    value++;

	/* Look up keyword in config tables */
	if (!cvtsudoers_parse_keyword(conf_file, keyword, value, cvtsudoers_conf_vars))
	    sudo_warnx(U_("%s: unknown key word: %s"), conf_file, keyword);
    }
    free(line);
    fclose(fp);

    debug_return_ptr(&cvtsudoers_config);
}

static void
cvtsudoers_conf_free(struct cvtsudoers_config *conf)
{
    debug_decl(cvtsudoers_conf_free, SUDOERS_DEBUG_UTIL)

    if (conf != NULL) {
	free(conf->sudoers_base);
	free(conf->input_format);
	free(conf->output_format);
	conf->sudoers_base = NULL;
	conf->input_format = NULL;
	conf->output_format = NULL;
    }

    debug_return;
}

static int
cvtsudoers_parse_defaults(char *expression)
{
    char *last, *cp = expression;
    int flags = 0;
    debug_decl(cvtsudoers_parse_defaults, SUDOERS_DEBUG_UTIL)

    for ((cp = strtok_r(cp, ",", &last)); cp != NULL; (cp = strtok_r(NULL, ",", &last))) {
	if (strcasecmp(cp, "all") == 0) {
	    SET(flags, CVT_DEFAULTS_ALL);
	} else if (strcasecmp(cp, "global") == 0) {
	    SET(flags, CVT_DEFAULTS_GLOBAL);
	} else if (strcasecmp(cp, "user") == 0) {
	    SET(flags, CVT_DEFAULTS_USER);
	} else if (strcasecmp(cp, "runas") == 0) {
	    SET(flags, CVT_DEFAULTS_RUNAS);
	} else if (strcasecmp(cp, "host") == 0) {
	    SET(flags, CVT_DEFAULTS_HOST);
	} else if (strcasecmp(cp, "command") == 0) {
	    SET(flags, CVT_DEFAULTS_CMND);
	} else {
	    sudo_warnx(U_("invalid defaults type: %s"), cp);
	    debug_return_int(-1);
	}
    }

    debug_return_int(flags);
}

static int
cvtsudoers_parse_suppression(char *expression)
{
    char *last, *cp = expression;
    int flags = 0;
    debug_decl(cvtsudoers_parse_suppression, SUDOERS_DEBUG_UTIL)

    for ((cp = strtok_r(cp, ",", &last)); cp != NULL; (cp = strtok_r(NULL, ",", &last))) {
	if (strcasecmp(cp, "defaults") == 0) {
	    SET(flags, SUPPRESS_DEFAULTS);
	} else if (strcasecmp(cp, "aliases") == 0) {
	    SET(flags, SUPPRESS_ALIASES);
	} else if (strcasecmp(cp, "privileges") == 0 || strcasecmp(cp, "privs") == 0) {
	    SET(flags, SUPPRESS_PRIVS);
	} else {
	    sudo_warnx(U_("invalid suppression type: %s"), cp);
	    debug_return_int(-1);
	}
    }

    debug_return_int(flags);
}

static bool
cvtsudoers_parse_filter(char *expression)
{
    char *last, *cp = expression;
    debug_decl(cvtsudoers_parse_filter, SUDOERS_DEBUG_UTIL)

    if (filters == NULL) {
	if ((filters = malloc(sizeof(*filters))) == NULL) {
	    sudo_fatalx(U_("%s: %s"), __func__,
		U_("unable to allocate memory"));
	}
	STAILQ_INIT(&filters->users);
	STAILQ_INIT(&filters->groups);
	STAILQ_INIT(&filters->hosts);
    }

    for ((cp = strtok_r(cp, ",", &last)); cp != NULL; (cp = strtok_r(NULL, ",", &last))) {
	/*
	 * Filter expression:
	 *	user=foo,group=bar,host=baz
	 */
	char *keyword;
	struct sudoers_string *s;

	if ((s = malloc(sizeof(*s))) == NULL) {
	    sudo_fatalx(U_("%s: %s"), __func__,
		U_("unable to allocate memory"));
	}

	/* Parse keyword = value */
	keyword = cp;
	if ((cp = strchr(cp, '=')) == NULL) {
	    sudo_warnx(U_("invalid filter: %s"), keyword);;
	    free(s);
	    debug_return_bool(false);
	}
	*cp++ = '\0';
	s->str = cp;

	if (strcmp(keyword, "user") == 0 ){
	    STAILQ_INSERT_TAIL(&filters->users, s, entries);
	} else if (strcmp(keyword, "group") == 0 ){
	    STAILQ_INSERT_TAIL(&filters->groups, s, entries);
	} else if (strcmp(keyword, "host") == 0 ){
	    STAILQ_INSERT_TAIL(&filters->hosts, s, entries);
	} else {
	    sudo_warnx(U_("invalid filter: %s"), keyword);;
	    free(s);
	    debug_return_bool(false);
	}
    }

    debug_return_bool(true);
}

static bool
parse_ldif(struct sudoers_parse_tree *parse_tree, const char *input_file,
    struct cvtsudoers_config *conf)
{
    FILE *fp = stdin;
    debug_decl(parse_ldif, SUDOERS_DEBUG_UTIL)

    /* Open LDIF file and parse it. */
    if (strcmp(input_file, "-") != 0) {
	if ((fp = fopen(input_file, "r")) == NULL)
	    sudo_fatal(U_("unable to open %s"), input_file);
    }

    debug_return_bool(sudoers_parse_ldif(parse_tree, fp, conf->sudoers_base,
	conf->store_options));
}

static bool
parse_sudoers(const char *input_file, struct cvtsudoers_config *conf)
{
    debug_decl(parse_sudoers, SUDOERS_DEBUG_UTIL)

    /* Open sudoers file and parse it. */
    if (strcmp(input_file, "-") == 0) {
	sudoersin = stdin;
	input_file = "stdin";
    } else if ((sudoersin = fopen(input_file, "r")) == NULL)
	sudo_fatal(U_("unable to open %s"), input_file);
    init_parser(input_file, false);
    if (sudoersparse() && !parse_error) {
	sudo_warnx(U_("failed to parse %s file, unknown error"), input_file);
	parse_error = true;
	rcstr_delref(errorfile);
	if ((errorfile = rcstr_dup(input_file)) == NULL)
	    sudo_fatalx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
    }
    if (parse_error) {
	if (errorlineno != -1)
	    sudo_warnx(U_("parse error in %s near line %d\n"),
		errorfile, errorlineno);
	else if (errorfile != NULL)
	    sudo_warnx(U_("parse error in %s\n"), errorfile);
	debug_return_bool(false);
    }
    debug_return_bool(true);
}

FILE *
open_sudoers(const char *sudoers, bool doedit, bool *keepopen)
{
    return fopen(sudoers, "r");
}

static bool
userlist_matches_filter(struct sudoers_parse_tree *parse_tree,
    struct member_list *users, struct cvtsudoers_config *conf)
{
    struct sudoers_string *s;
    struct member *m, *next;
    bool ret = false;
    debug_decl(userlist_matches_filter, SUDOERS_DEBUG_UTIL)

    if (filters == NULL ||
	(STAILQ_EMPTY(&filters->users) && STAILQ_EMPTY(&filters->groups)))
	debug_return_bool(true);

    TAILQ_FOREACH_REVERSE_SAFE(m, users, member_list, entries, next) {
	bool matched = false;

	if (STAILQ_EMPTY(&filters->users)) {
	    struct passwd pw;

	    /*
	     * Only groups in filter, make a dummy user so userlist_matches()
	     * can do its thing.
	     */
	    memset(&pw, 0, sizeof(pw));
	    pw.pw_name = "_nobody";
	    pw.pw_uid = (uid_t)-1;
	    pw.pw_gid = (gid_t)-1;

	    if (user_matches(parse_tree, &pw, m) == true)
		matched = true;
	} else {
	    STAILQ_FOREACH(s, &filters->users, entries) {
		struct passwd *pw = NULL;

		/* An upper case filter entry may be a User_Alias */
		/* XXX - doesn't handle nested aliases */
		if (m->type == ALIAS && !conf->expand_aliases) {
		    if (strcmp(m->name, s->str) == 0) {
			matched = true;
			break;
		    }
		}

		if (s->str[0] == '#') {
		    const char *errstr;
		    uid_t uid = sudo_strtoid(s->str + 1, NULL, NULL, &errstr);
		    if (errstr == NULL)
			pw = sudo_getpwuid(uid);
		}
		if (pw == NULL)
		    pw = sudo_getpwnam(s->str);
		if (pw == NULL)
		    continue;

		if (user_matches(parse_tree, pw, m) == true)
		    matched = true;
		sudo_pw_delref(pw);

		/* Only need one user in the filter to match. */
		if (matched)
		    break;
	    }
	}

	if (matched) {
	    ret = true;
	} else if (conf->prune_matches) {
	    TAILQ_REMOVE(users, m, entries);
	    free_member(m);
	}
    }

    debug_return_bool(ret);
}

static bool
hostlist_matches_filter(struct sudoers_parse_tree *parse_tree,
    struct member_list *hostlist, struct cvtsudoers_config *conf)
{
    struct sudoers_string *s;
    struct member *m, *next;
    char *lhost, *shost;
    bool ret = false;
    char **shosts;
    int n = 0;
    debug_decl(hostlist_matches_filter, SUDOERS_DEBUG_UTIL)

    if (filters == NULL || STAILQ_EMPTY(&filters->hosts))
	debug_return_bool(true);

    /* Create an array of short host names. */
    STAILQ_FOREACH(s, &filters->hosts, entries) {
	n++;
    }
    shosts = reallocarray(NULL, n, sizeof(char *));
    if (shosts == NULL)
	sudo_fatalx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
    n = 0;
    STAILQ_FOREACH(s, &filters->hosts, entries) {
	lhost = s->str;
	if ((shost = strchr(lhost, '.')) != NULL) {
	    shost = strndup(lhost, (size_t)(shost - lhost));
	    if (shost == NULL) {
		sudo_fatalx(U_("%s: %s"), __func__,
		    U_("unable to allocate memory"));
	    }
	} else {
	    shost = lhost;
	}
	shosts[n++] = shost;
    }

    TAILQ_FOREACH_REVERSE_SAFE(m, hostlist, member_list, entries, next) {
	bool matched = false;
	n = 0;
	STAILQ_FOREACH(s, &filters->hosts, entries) {
	    lhost = s->str;
	    shost = shosts[n++];

	    /* An upper case filter entry may be a Host_Alias */
	    /* XXX - doesn't handle nested aliases */
	    if (m->type == ALIAS && !conf->expand_aliases) {
		if (strcmp(m->name, s->str) == 0) {
		    matched = true;
		    break;
		}
	    }

	    /* Only need one host in the filter to match. */
	    /* XXX - can't use netgroup_tuple with NULL pw */
	    if (host_matches(parse_tree, NULL, lhost, shost, m) == true) {
		matched = true;
		break;
	    }
	}

	if (matched) {
	    ret = true;
	} else if (conf->prune_matches) {
	    TAILQ_REMOVE(hostlist, m, entries);
	    free_member(m);
	}
    }

    /* Free shosts array and its contents. */
    n = 0;
    STAILQ_FOREACH(s, &filters->hosts, entries) {
	lhost = s->str;
	shost = shosts[n++];
	if (shost != lhost)
	    free(shost);
    }
    free(shosts);

    debug_return_bool(ret == true);
}

/*
 * Display Defaults entries
 */
static bool
print_defaults_sudoers(struct sudoers_parse_tree *parse_tree,
    struct sudo_lbuf *lbuf, bool expand_aliases)
{
    struct defaults *def, *next;
    debug_decl(print_defaults_sudoers, SUDOERS_DEBUG_UTIL)

    TAILQ_FOREACH_SAFE(def, &parse_tree->defaults, entries, next) {
	sudoers_format_default_line(lbuf, parse_tree, def, &next,
	    expand_aliases);
    }

    debug_return_bool(!sudo_lbuf_error(lbuf));
}

static int
print_alias_sudoers(struct sudoers_parse_tree *parse_tree, struct alias *a,
    void *v)
{
    struct sudo_lbuf *lbuf = v;
    struct member *m;
    debug_decl(print_alias_sudoers, SUDOERS_DEBUG_UTIL)

    sudo_lbuf_append(lbuf, "%s %s = ", alias_type_to_string(a->type),
	a->name);
    TAILQ_FOREACH(m, &a->members, entries) {
	if (m != TAILQ_FIRST(&a->members))
	    sudo_lbuf_append(lbuf, ", ");
	sudoers_format_member(lbuf, parse_tree, m, NULL, UNSPEC);
    }
    sudo_lbuf_append(lbuf, "\n");

    debug_return_int(sudo_lbuf_error(lbuf) ? -1 : 0);
}

/*
 * Display aliases
 */
static bool
print_aliases_sudoers(struct sudoers_parse_tree *parse_tree,
    struct sudo_lbuf *lbuf)
{
    debug_decl(print_aliases_sudoers, SUDOERS_DEBUG_UTIL)

    alias_apply(parse_tree, print_alias_sudoers, lbuf);

    debug_return_bool(!sudo_lbuf_error(lbuf));
}

static FILE *output_fp;		/* global for convert_sudoers_output */

static int
convert_sudoers_output(const char *buf)
{
    return fputs(buf, output_fp);
}

/*
 * Apply filters to userspecs, removing non-matching entries.
 */
static void
filter_userspecs(struct sudoers_parse_tree *parse_tree,
    struct cvtsudoers_config *conf)
{
    struct userspec *us, *next_us;
    struct privilege *priv, *next_priv;
    debug_decl(filter_userspecs, SUDOERS_DEBUG_UTIL)

    if (filters == NULL)
	debug_return;

    /*
     * Does not currently prune out non-matching entries in the user or
     * host lists.  It acts more like a grep than a true filter.
     * In the future, we may want to add a prune option.
     */
    TAILQ_FOREACH_SAFE(us, &parse_tree->userspecs, entries, next_us) {
	if (!userlist_matches_filter(parse_tree, &us->users, conf)) {
	    TAILQ_REMOVE(&parse_tree->userspecs, us, entries);
	    free_userspec(us);
	    continue;
	}
	TAILQ_FOREACH_SAFE(priv, &us->privileges, entries, next_priv) {
	    if (!hostlist_matches_filter(parse_tree, &priv->hostlist, conf)) {
		TAILQ_REMOVE(&us->privileges, priv, entries);
		free_privilege(priv);
	    }
	}
	if (TAILQ_EMPTY(&us->privileges)) {
	    TAILQ_REMOVE(&parse_tree->userspecs, us, entries);
	    free_userspec(us);
	    continue;
	}
    }
    debug_return;
}

/*
 * Check whether the alias described by "alias_name" is the same
 * as "name" or includes an alias called "name".
 * Returns true if matched, else false.
 */
static bool
alias_matches(struct sudoers_parse_tree *parse_tree, const char *name,
    const char *alias_name, int alias_type)
{
    struct alias *a;
    struct member *m;
    bool ret = false;
    debug_decl(alias_matches, SUDOERS_DEBUG_ALIAS)

    if (strcmp(name, alias_name) == 0)
	debug_return_bool(true);

    a = alias_get(parse_tree, alias_name, alias_type);
    if (a != NULL) {
	TAILQ_FOREACH(m, &a->members, entries) {
	    if (m->type != ALIAS)
		continue;
	    if (alias_matches(parse_tree, name, m->name, alias_type)) {
		ret = true;
		break;
	    }
	}
	alias_put(a);
    }

    debug_return_bool(ret);
}

/*
 * Check whether userspecs uses the aliases in the specified member lists.
 * If used, they are removed (and freed) from the list.
 * This does *not* check Defaults for used aliases, only userspecs.
 */
static void
alias_used_by_userspecs(struct sudoers_parse_tree *parse_tree,
    struct member_list *user_aliases, struct member_list *runas_aliases,
    struct member_list *host_aliases, struct member_list *cmnd_aliases)
{
    struct privilege *priv, *priv_next;
    struct userspec *us, *us_next;
    struct cmndspec *cs, *cs_next;
    struct member *m, *m_next;
    struct member *am, *am_next;
    debug_decl(alias_used_by_userspecs, SUDOERS_DEBUG_ALIAS)

    /* Iterate over the policy, checking for aliases. */
    TAILQ_FOREACH_SAFE(us, &parse_tree->userspecs, entries, us_next) {
	TAILQ_FOREACH_SAFE(m, &us->users, entries, m_next) {
	    if (m->type == ALIAS) {
		/* If alias is used, remove from user_aliases and free. */
		TAILQ_FOREACH_SAFE(am, user_aliases, entries, am_next) {
		    if (alias_matches(parse_tree, am->name, m->name, USERALIAS)) {
			TAILQ_REMOVE(user_aliases, am, entries);
			free_member(am);
		    }
		}
	    }
	}
	TAILQ_FOREACH_SAFE(priv, &us->privileges, entries, priv_next) {
	    TAILQ_FOREACH(m, &priv->hostlist, entries) {
		if (m->type == ALIAS) {
		    /* If alias is used, remove from host_aliases and free. */
		    TAILQ_FOREACH_SAFE(am, host_aliases, entries, am_next) {
			if (alias_matches(parse_tree, am->name, m->name, HOSTALIAS)) {
			    TAILQ_REMOVE(host_aliases, am, entries);
			    free_member(am);
			}
		    }
		}
	    }
	    TAILQ_FOREACH_SAFE(cs, &priv->cmndlist, entries, cs_next) {
		if (cs->runasuserlist != NULL) {
		    TAILQ_FOREACH_SAFE(m, cs->runasuserlist, entries, m_next) {
			if (m->type == ALIAS) {
			    /* If alias is used, remove from runas_aliases and free. */
			    TAILQ_FOREACH_SAFE(am, runas_aliases, entries, am_next) {
				if (alias_matches(parse_tree, am->name, m->name, RUNASALIAS)) {
				    TAILQ_REMOVE(runas_aliases, am, entries);
				    free_member(am);
				}
			    }
			}
		    }
		}
		if (cs->runasgrouplist != NULL) {
		    TAILQ_FOREACH_SAFE(m, cs->runasgrouplist, entries, m_next) {
			if (m->type == ALIAS) {
			    /* If alias is used, remove from runas_aliases and free. */
			    TAILQ_FOREACH_SAFE(am, runas_aliases, entries, am_next) {
				if (alias_matches(parse_tree, am->name, m->name, RUNASALIAS)) {
				    TAILQ_REMOVE(runas_aliases, am, entries);
				    free_member(am);
				}
			    }
			}
		    }
		}
		if ((m = cs->cmnd)->type == ALIAS) {
		    /* If alias is used, remove from cmnd_aliases and free. */
		    TAILQ_FOREACH_SAFE(am, cmnd_aliases, entries, am_next) {
			if (alias_matches(parse_tree, am->name, m->name, CMNDALIAS)) {
			    TAILQ_REMOVE(cmnd_aliases, am, entries);
			    free_member(am);
			}
		    }
		}
	    }
	}
    }

    debug_return;
}

/*
 * Apply filters to host/user-based Defaults, removing non-matching entries.
 */
static void
filter_defaults(struct sudoers_parse_tree *parse_tree,
    struct cvtsudoers_config *conf)
{
    struct member_list user_aliases = TAILQ_HEAD_INITIALIZER(user_aliases);
    struct member_list runas_aliases = TAILQ_HEAD_INITIALIZER(runas_aliases);
    struct member_list host_aliases = TAILQ_HEAD_INITIALIZER(host_aliases);
    struct member_list cmnd_aliases = TAILQ_HEAD_INITIALIZER(cmnd_aliases);
    struct member_list *prev_binding = NULL;
    struct defaults *def, *def_next;
    struct member *m, *m_next;
    struct alias *a;
    int alias_type;
    debug_decl(filter_defaults, SUDOERS_DEBUG_DEFAULTS)

    if (filters == NULL && conf->defaults == CVT_DEFAULTS_ALL)
	debug_return;

    TAILQ_FOREACH_SAFE(def, &parse_tree->defaults, entries, def_next) {
	bool keep = true;

	switch (def->type) {
	case DEFAULTS:
	    if (!ISSET(conf->defaults, CVT_DEFAULTS_GLOBAL))
		keep = false;
	    alias_type = UNSPEC;
	    break;
	case DEFAULTS_USER:
	    if (!ISSET(conf->defaults, CVT_DEFAULTS_USER) ||
		!userlist_matches_filter(parse_tree, def->binding, conf))
		keep = false;
	    alias_type = USERALIAS;
	    break;
	case DEFAULTS_RUNAS:
	    if (!ISSET(conf->defaults, CVT_DEFAULTS_RUNAS))
		keep = false;
	    alias_type = RUNASALIAS;
	    break;
	case DEFAULTS_HOST:
	    if (!ISSET(conf->defaults, CVT_DEFAULTS_HOST) ||
		!hostlist_matches_filter(parse_tree, def->binding, conf))
		keep = false;
	    alias_type = HOSTALIAS;
	    break;
	case DEFAULTS_CMND:
	    if (!ISSET(conf->defaults, CVT_DEFAULTS_CMND))
		keep = false;
	    alias_type = CMNDALIAS;
	    break;
	default:
	    sudo_fatalx_nodebug("unexpected defaults type %d", def->type);
	    break;
	}

	if (!keep) {
	    /* Look for aliases used by the binding. */
	    /* XXX - move to function */
	    if (alias_type != UNSPEC && def->binding != prev_binding) {
		TAILQ_FOREACH_SAFE(m, def->binding, entries, m_next) {
		    if (m->type == ALIAS) {
			TAILQ_REMOVE(def->binding, m, entries);
			switch (alias_type) {
			case USERALIAS:
			    TAILQ_INSERT_TAIL(&user_aliases, m, entries);
			    break;
			case RUNASALIAS:
			    TAILQ_INSERT_TAIL(&runas_aliases, m, entries);
			    break;
			case HOSTALIAS:
			    TAILQ_INSERT_TAIL(&host_aliases, m, entries);
			    break;
			case CMNDALIAS:
			    TAILQ_INSERT_TAIL(&cmnd_aliases, m, entries);
			    break;
			default:
			    sudo_fatalx_nodebug("unexpected alias type %d",
				alias_type);
			    break;
			}
		    }
		}
	    }
	    TAILQ_REMOVE(&parse_tree->defaults, def, entries);
	    free_default(def, &prev_binding);
	    if (prev_binding != NULL) {
		/* Remove and free Defaults that share the same binding. */
		while (def_next != NULL && def_next->binding == prev_binding) {
		    def = def_next;
		    def_next = TAILQ_NEXT(def, entries);
		    TAILQ_REMOVE(&parse_tree->defaults, def, entries);
		    free_default(def, &prev_binding);
		}
	    }
	} else {
	    prev_binding = def->binding;
	}
    }

    /* Remove now-unreferenced aliases. */
    alias_used_by_userspecs(parse_tree, &user_aliases, &runas_aliases,
	&host_aliases, &cmnd_aliases);
    TAILQ_FOREACH_SAFE(m, &user_aliases, entries, m_next) {
	a = alias_remove(parse_tree, m->name, USERALIAS);
	alias_free(a);
	free_member(m);
    }
    TAILQ_FOREACH_SAFE(m, &runas_aliases, entries, m_next) {
	a = alias_remove(parse_tree, m->name, RUNASALIAS);
	alias_free(a);
	free_member(m);
    }
    TAILQ_FOREACH_SAFE(m, &host_aliases, entries, m_next) {
	a = alias_remove(parse_tree, m->name, HOSTALIAS);
	alias_free(a);
	free_member(m);
    }
    TAILQ_FOREACH_SAFE(m, &cmnd_aliases, entries, m_next) {
	a = alias_remove(parse_tree, m->name, CMNDALIAS);
	alias_free(a);
	free_member(m);
    }

    debug_return;
}

/*
 * Remove unreferenced aliases.
 */
static void
alias_remove_unused(struct sudoers_parse_tree *parse_tree)
{
    struct rbtree *used_aliases;
    debug_decl(alias_remove_unused, SUDOERS_DEBUG_ALIAS)

    used_aliases = alloc_aliases();
    if (used_aliases == NULL)
	sudo_fatalx(U_("%s: %s"), __func__, U_("unable to allocate memory"));

    /* Move all referenced aliases to used_aliases. */
    if (!alias_find_used(parse_tree, used_aliases))
	sudo_fatalx(U_("%s: %s"), __func__, U_("unable to allocate memory"));

    /* Only unreferenced aliases are left, swap and free the unused ones. */
    free_aliases(parse_tree->aliases);
    parse_tree->aliases = used_aliases;

    debug_return;
}

/*
 * Prune out non-matching entries from user and host aliases.
 */
static int
alias_prune_helper(struct sudoers_parse_tree *parse_tree, struct alias *a,
    void *v)
{
    struct cvtsudoers_config *conf = v;

    /* XXX - misue of these functions */
    switch (a->type) {
    case USERALIAS:
	userlist_matches_filter(parse_tree, &a->members, conf);
	break;
    case HOSTALIAS:
	hostlist_matches_filter(parse_tree, &a->members, conf);
	break;
    default:
	break;
    }

    return 0;
}

/*
 * Prune out non-matching entries from within aliases.
 */
static void
alias_prune(struct sudoers_parse_tree *parse_tree,
    struct cvtsudoers_config *conf)
{
    debug_decl(alias_prune, SUDOERS_DEBUG_ALIAS)

    alias_apply(parse_tree, alias_prune_helper, conf);

    debug_return;
}

/*
 * Convert back to sudoers.
 */
static bool
convert_sudoers_sudoers(struct sudoers_parse_tree *parse_tree,
    const char *output_file, struct cvtsudoers_config *conf)
{
    bool ret = true;
    struct sudo_lbuf lbuf;
    debug_decl(convert_sudoers_sudoers, SUDOERS_DEBUG_UTIL)

    if (strcmp(output_file, "-") == 0) {
	output_fp = stdout;
    } else {
	if ((output_fp = fopen(output_file, "w")) == NULL)
	    sudo_fatal(U_("unable to open %s"), output_file);
    }

    /* Wrap lines at 80 columns with a 4 character indent. */
    sudo_lbuf_init(&lbuf, convert_sudoers_output, 4, "\\", 80);

    /* Print Defaults */
    if (!ISSET(conf->suppress, SUPPRESS_DEFAULTS)) {
	if (!print_defaults_sudoers(parse_tree, &lbuf, conf->expand_aliases))
	    goto done;
	if (lbuf.len > 0) {
	    sudo_lbuf_print(&lbuf);
	    sudo_lbuf_append(&lbuf, "\n");
	}
    }

    /* Print Aliases */
    if (!conf->expand_aliases && !ISSET(conf->suppress, SUPPRESS_ALIASES)) {
	if (!print_aliases_sudoers(parse_tree, &lbuf))
	    goto done;
	if (lbuf.len > 1) {
	    sudo_lbuf_print(&lbuf);
	    sudo_lbuf_append(&lbuf, "\n");
	}
    }

    /* Print User_Specs, separated by blank lines. */
    if (!ISSET(conf->suppress, SUPPRESS_PRIVS)) {
	if (!sudoers_format_userspecs(&lbuf, parse_tree, "\n",
	    conf->expand_aliases, true)) {
	    goto done;
	}
	if (lbuf.len > 1) {
	    sudo_lbuf_print(&lbuf);
	}
    }

done:
    if (sudo_lbuf_error(&lbuf)) {
	if (errno == ENOMEM)
	    sudo_fatalx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
	ret = false;
    }
    sudo_lbuf_destroy(&lbuf);

    (void)fflush(output_fp);
    if (ferror(output_fp)) {
	sudo_warn(U_("unable to write to %s"), output_file);
	ret = false;
    }
    if (output_fp != stdout)
	fclose(output_fp);

    debug_return_bool(ret);
}

static void
usage(int fatal)
{
    (void) fprintf(fatal ? stderr : stdout, "usage: %s [-ehMpV] [-b dn] "
	"[-c conf_file ] [-d deftypes] [-f output_format] [-i input_format] "
	"[-I increment] [-m filter] [-o output_file] [-O start_point] "
	"[-P padding] [-s sections] [input_file]\n", getprogname());
    if (fatal)
	exit(1);
}

static void
help(void)
{
    (void) printf(_("%s - convert between sudoers file formats\n\n"), getprogname());
    usage(0);
    (void) puts(_("\nOptions:\n"
	"  -b, --base=dn              the base DN for sudo LDAP queries\n"
	"  -c, --config=conf_file     the path to the configuration file\n"
	"  -d, --defaults=deftypes    only convert Defaults of the specified types\n"
	"  -e, --expand-aliases       expand aliases when converting\n"
	"  -f, --output-format=format set output format: JSON, LDIF or sudoers\n"
	"  -i, --input-format=format  set input format: LDIF or sudoers\n"
	"  -I, --increment=num        amount to increase each sudoOrder by\n"
	"  -h, --help                 display help message and exit\n"
	"  -m, --match=filter         only convert entries that match the filter\n"
	"  -M, --match-local          match filter uses passwd and group databases\n"
	"  -o, --output=output_file   write converted sudoers to output_file\n"
	"  -O, --order-start=num      starting point for first sudoOrder\n"
	"  -p, --prune-matches        prune non-matching users, groups and hosts\n"
	"  -P, --padding=num          base padding for sudoOrder increment\n"
	"  -s, --suppress=sections    suppress output of certain sections\n"
	"  -V, --version              display version information and exit"));
    exit(0);
}