summaryrefslogtreecommitdiff
path: root/subversion/libsvn_repos/authz_parse.c
blob: e2964de94003c896115c64448302d2297782f966 (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
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
/* authz_parse.c : Parser for path-based access control
 *
 * ====================================================================
 *    Licensed to the Apache Software Foundation (ASF) under one
 *    or more contributor license agreements.  See the NOTICE file
 *    distributed with this work for additional information
 *    regarding copyright ownership.  The ASF licenses this file
 *    to you under the Apache License, Version 2.0 (the
 *    "License"); you may not use this file except in compliance
 *    with the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing,
 *    software distributed under the License is distributed on an
 *    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *    KIND, either express or implied.  See the License for the
 *    specific language governing permissions and limitations
 *    under the License.
 * ====================================================================
 */

#include <apr_fnmatch.h>
#include <apr_tables.h>

#include "svn_ctype.h"
#include "svn_error.h"
#include "svn_hash.h"
#include "svn_iter.h"
#include "svn_pools.h"
#include "svn_repos.h"

#include "private/svn_fspath.h"
#include "private/svn_config_private.h"
#include "private/svn_sorts_private.h"
#include "private/svn_string_private.h"
#include "private/svn_subr_private.h"

#include "svn_private_config.h"

#include "authz.h"


/* Temporary ACL constructed by the parser. */
typedef struct parsed_acl_t
{
  /* The global ACL.
     The strings in ACL.rule are allocated from the result pool.
     ACL.user_access is null during the parsing stage. */
  authz_acl_t acl;

  /* The set of access control entries. In the second pass, aliases in
     these entries will be expanded and equivalent entries will be
     merged. The entries are allocated from the parser pool. */
  apr_hash_t *aces;

  /* The set of access control entries that use aliases. In the second
     pass, aliases in these entries will be expanded and merged into ACES.
     The entries are allocated from the parser pool. */
  apr_hash_t *alias_aces;
} parsed_acl_t;


/* Temporary group definition constructed by the authz/group parser.
   Once all groups and aliases are defined, a second pass over these
   data will recursively expand group memberships. */
typedef struct parsed_group_t
{
  svn_boolean_t local_group;
  apr_array_header_t *members;
} parsed_group_t;


/* Baton for the parser constructor. */
typedef struct ctor_baton_t
{
  /* The final output of the parser. */
  authz_full_t *authz;

  /* Interned-string set, allocated in AUTHZ->pool.
     Stores singleton instances of user, group and repository names,
     which are used by members of the AUTHZ structure. By reusing the
     same immutable string multiple times, we reduce the size of the
     authz representation in the result pool.

     N.B.: Whilst the strings are allocated from teh result pool, the
     hash table itself is not. */
  apr_hash_t *strings;

  /* A set of all the sections that were seen in the authz or global
     groups file. Rules, aliases and groups may each only be defined
     once in the authz file. The global groups file may only contain a
     [groups] section. */
  apr_hash_t *sections;

  /* The name of the section we're currently parsing. */
  const char *section;

  /* TRUE iff we're parsing the global groups file. */
  svn_boolean_t parsing_groups;

  /* TRUE iff we're parsing a [groups] section. */
  svn_boolean_t in_groups;

  /* TRUE iff we're parsing an [aliases] section. */
  svn_boolean_t in_aliases;

  /* A set of all the unique rules we parsed from the section names. */
  apr_hash_t *parsed_rules;

  /* Temporary parsed-groups definitions. */
  apr_hash_t *parsed_groups;

  /* Temporary alias mappings. */
  apr_hash_t *parsed_aliases;

  /* Temporary parsed-acl definitions. */
  apr_array_header_t *parsed_acls;

  /* Temporary expanded groups definitions. */
  apr_hash_t *expanded_groups;

  /* The temporary ACL we're currently constructing. */
  parsed_acl_t *current_acl;

  /* Temporary buffers used to parse a rule into segments. */
  svn_membuf_t rule_path_buffer;
  svn_stringbuf_t *rule_string_buffer;

  /* The warning callback and its baton. */
  svn_repos_authz_warning_func_t warning_func;
  void *warning_baton;

  /* The parser's scratch pool. This may not be the same pool as
     passed to the constructor callbacks, that is supposed to be an
     iteration pool maintained by the generic parser.

     N.B.: The result pool is AUTHZ->pool. */
  apr_pool_t *parser_pool;
} ctor_baton_t;


/* An empty string with a known address. */
static const char interned_empty_string[] = "";

/* The name of the aliases section. */
static const char aliases_section[] = "aliases";

/* The name of the groups section. */
static const char groups_section[] = "groups";

/* The token indicating that an authz rule contains wildcards. */
static const char glob_rule_token[] = "glob";

/* The anonymous access token. */
static const char anon_access_token[] = "$anonymous";

/* The authenticated access token. */
static const char authn_access_token[] = "$authenticated";

/* Fake token for inverted rights. */
static const char neg_access_token[] = "~~$inverted";

/* Initialize a rights structure.
   The minimum rights start with all available access and are later
   bitwise-and'ed with actual access rights. The maximum rights begin
   empty and are later bitwise-and'ed with actual rights. */
static void init_rights(authz_rights_t *rights)
{
  rights->min_access = authz_access_write;
  rights->max_access = authz_access_none;
 }

/* Initialize a global rights structure.
   The USER string must be interned or statically initialized. */
static void
init_global_rights(authz_global_rights_t *gr, const char *user,
                   apr_pool_t *result_pool)
{
  gr->user = user;
  init_rights(&gr->all_repos_rights);
  init_rights(&gr->any_repos_rights);
  gr->per_repos_rights = apr_hash_make(result_pool);
}


/* Insert the default global ACL into the parsed ACLs. */
static void
insert_default_acl(ctor_baton_t *cb)
{
  parsed_acl_t *acl = &APR_ARRAY_PUSH(cb->parsed_acls, parsed_acl_t);
  acl->acl.sequence_number = 0;
  acl->acl.rule.repos = interned_empty_string;
  acl->acl.rule.len = 0;
  acl->acl.rule.path = NULL;
  acl->acl.anon_access = authz_access_none;
  acl->acl.has_anon_access = TRUE;
  acl->acl.authn_access = authz_access_none;
  acl->acl.has_authn_access = TRUE;
  acl->acl.neg_access = authz_access_none;
  acl->acl.has_neg_access = TRUE;
  acl->acl.user_access = NULL;
  acl->aces = svn_hash__make(cb->parser_pool);
  acl->alias_aces = svn_hash__make(cb->parser_pool);
}


/* Initialize a constuctor baton. */
static ctor_baton_t *
create_ctor_baton(svn_repos_authz_warning_func_t warning_func,
                  void *warning_baton,
                  apr_pool_t *result_pool,
                  apr_pool_t *scratch_pool)
{
  apr_pool_t *const parser_pool = svn_pool_create(scratch_pool);
  ctor_baton_t *const cb = apr_pcalloc(parser_pool, sizeof(*cb));

  authz_full_t *const authz = apr_pcalloc(result_pool, sizeof(*authz));
  init_global_rights(&authz->anon_rights, anon_access_token, result_pool);
  init_global_rights(&authz->authn_rights, authn_access_token, result_pool);
  init_global_rights(&authz->neg_rights, neg_access_token, result_pool);
  authz->user_rights = svn_hash__make(result_pool);
  authz->pool = result_pool;

  cb->authz = authz;
  cb->strings = svn_hash__make(parser_pool);

  cb->sections = svn_hash__make(parser_pool);
  cb->section = NULL;
  cb->parsing_groups = FALSE;
  cb->in_groups = FALSE;
  cb->in_aliases = FALSE;

  cb->parsed_rules = svn_hash__make(parser_pool);
  cb->parsed_groups = svn_hash__make(parser_pool);
  cb->parsed_aliases = svn_hash__make(parser_pool);
  cb->parsed_acls = apr_array_make(parser_pool, 64, sizeof(parsed_acl_t));
  cb->current_acl = NULL;

  svn_membuf__create(&cb->rule_path_buffer, 0, parser_pool);
  cb->rule_string_buffer = svn_stringbuf_create_empty(parser_pool);

  cb->warning_func = warning_func;
  cb->warning_baton = warning_baton;

  cb->parser_pool = parser_pool;

  insert_default_acl(cb);

  return cb;
}


/* Emit a warning. Clears ERROR */
static void
emit_parser_warning(const ctor_baton_t *cb,
                    svn_error_t *error,
                    apr_pool_t *scratch_pool)
{
  if (cb->warning_func)
    cb->warning_func(cb->warning_baton, error, scratch_pool);
  svn_error_clear(error);
}

/* Avoid creating an error struct if there is no warning function. */
#define SVN_AUTHZ_PARSE_WARN(cb, err, pool)     \
  do {                                          \
    if ((cb) && (cb)->warning_func)             \
      emit_parser_warning((cb), (err), (pool)); \
  } while(0)


/* Create and store per-user global rights.
   The USER string must be interned or statically initialized. */
static void
prepare_global_rights(ctor_baton_t *cb, const char *user)
{
  authz_global_rights_t *gr = svn_hash_gets(cb->authz->user_rights, user);
  if (!gr)
    {
      gr = apr_palloc(cb->authz->pool, sizeof(*gr));
      init_global_rights(gr, user, cb->authz->pool);
      svn_hash_sets(cb->authz->user_rights, gr->user, gr);
    }
}


/* Internalize a string that will be referenced by the parsed svn_authz_t.
   If LEN is (apr_size_t)-1, assume the string is NUL-terminated. */
static const char *
intern_string(ctor_baton_t *cb, const char *str, apr_size_t len)
{
  const char *interned;

  if (len == (apr_size_t)-1)
    len = strlen(str);

  interned = apr_hash_get(cb->strings, str, len);
  if (!interned)
    {
      interned = apr_pstrmemdup(cb->authz->pool, str, len);
      apr_hash_set(cb->strings, interned, len, interned);
    }
  return interned;
}


/* Helper for rules_open_section and groups_open_section. */
static svn_error_t *
check_open_section(ctor_baton_t *cb, svn_stringbuf_t *section)
{
  SVN_ERR_ASSERT(!cb->current_acl && !cb->section);
  if (apr_hash_get(cb->sections, section->data, section->len))
    {
      if (cb->parsing_groups)
        return svn_error_createf(
            SVN_ERR_AUTHZ_INVALID_CONFIG, NULL,
            _("Section appears more than once"
              " in the global groups file: [%s]"),
            section->data);
      else
        return svn_error_createf(
            SVN_ERR_AUTHZ_INVALID_CONFIG, NULL,
            _("Section appears more than once"
              " in the authz file: [%s]"),
            section->data);
    }

  cb->section = apr_pstrmemdup(cb->parser_pool, section->data, section->len);
  svn_hash_sets(cb->sections,  cb->section, interned_empty_string);
  return SVN_NO_ERROR;
}


/* Constructor callback: Begins the [groups] section. */
static svn_error_t *
groups_open_section(void *baton, svn_stringbuf_t *section)
{
  ctor_baton_t *const cb = baton;

  if (cb->parsing_groups)
    SVN_ERR(check_open_section(cb, section));

  if (0 == strcmp(section->data, groups_section))
    {
      cb->in_groups = TRUE;
      return SVN_NO_ERROR;
    }

  return svn_error_createf(
      SVN_ERR_AUTHZ_INVALID_CONFIG, NULL,
      (cb->parsing_groups
       ? _("Section is not valid in the global group file: [%s]")
       : _("Section is not valid in the authz file: [%s]")),
      section->data);
}


/* Constructor callback: Parses a group declaration. */
static svn_error_t *
groups_add_value(void *baton, svn_stringbuf_t *section,
                 svn_stringbuf_t *option, svn_stringbuf_t *value)
{
  ctor_baton_t *const cb = baton;
  const char *group;
  apr_size_t group_len;

  SVN_ERR_ASSERT(cb->in_groups);

  if (strchr("@$&*~", *option->data))
    {
      if (cb->parsing_groups)
        return svn_error_createf(
            SVN_ERR_AUTHZ_INVALID_CONFIG, NULL,
            _("Global group name '%s' may not begin with '%c'"),
            option->data, *option->data);
      else
        return svn_error_createf(
            SVN_ERR_AUTHZ_INVALID_CONFIG, NULL,
            _("Group name '%s' may not begin with '%c'"),
            option->data, *option->data);
    }

  /* Decorate the name to make lookups consistent. */
  group = apr_pstrcat(cb->parser_pool, "@", option->data, SVN_VA_NULL);
  group_len = option->len + 1;
  if (apr_hash_get(cb->parsed_groups, group, group_len))
    {
      if (cb->parsing_groups)
        return svn_error_createf(SVN_ERR_AUTHZ_INVALID_CONFIG, NULL,
                                 _("Can't override definition"
                                   " of global group '%s'"),
                                 group);
      else
        return svn_error_createf(SVN_ERR_AUTHZ_INVALID_CONFIG, NULL,
                                 _("Can't override definition"
                                   " of group '%s'"),
                                 group);
    }

  /* We store the whole group definition, so that we can use the
     temporary groups in the baton hash later to fully expand group
     memberships.
     At this point, we can finally internalize the group name. */
  apr_hash_set(cb->parsed_groups,
               intern_string(cb, group, group_len), group_len,
               svn_cstring_split(value->data, ",", TRUE, cb->parser_pool));

  return SVN_NO_ERROR;
}


/* Remove escape sequences in-place. */
static void
unescape_in_place(svn_stringbuf_t *buf)
{
  char *p = buf->data;
  apr_size_t i;

  /* Skip the string up to the first escape sequence. */
  for (i = 0; i < buf->len; ++i)
    {
      if (*p == '\\')
        break;
      ++p;
    }

  if (i < buf->len)
    {
      /* Unescape the remainder of the string. */
      svn_boolean_t escape = TRUE;
      const char *q;

      for (q = p + 1, ++i; i < buf->len; ++i)
        {
          if (escape)
            {
              *p++ = *q++;
              escape = FALSE;
            }
          else if (*q == '\\')
            {
              ++q;
              escape = TRUE;
            }
          else
            *p++ = *q++;
        }

      /* A trailing backslash is literal, so make it part of the pattern. */
      if (escape)
        *p++ = '\\';
      *p = '\0';
      buf->len = p - buf->data;
    }
}


/* Internalize a pattern. */
static void
intern_pattern(ctor_baton_t *cb,
               svn_string_t *pattern,
               const char *string,
               apr_size_t len)
{
  pattern->data = intern_string(cb, string, len);
  pattern->len = len;
}


/* Parse a rule path PATH up to PATH_LEN into *RULE.
   If GLOB is TRUE, treat PATH as possibly containing wildcards.
   SECTION is the whole rule in the authz file.
   Use pools and buffers from CB to do the obvious thing. */
static svn_error_t *
parse_rule_path(authz_rule_t *rule,
                ctor_baton_t *cb,
                svn_boolean_t glob,
                const char *path,
                apr_size_t path_len,
                const char *section)
{
  svn_stringbuf_t *const pattern = cb->rule_string_buffer;
  const char *const path_end = path + path_len;
  authz_rule_segment_t *segment;
  const char *start;
  const char *end;
  int nseg;

  SVN_ERR_ASSERT(*path == '/');

  nseg = 0;
  for (start = path; start != path_end; start = end)
    {
      apr_size_t pattern_len;

      /* Skip the leading slash and find the end of the segment. */
      end = memchr(++start, '/', path_len - 1);
      if (!end)
        end = path_end;

      pattern_len = end - start;
      path_len -= pattern_len + 1;

      if (pattern_len == 0)
        {
          if (nseg == 0)
            {
              /* This is an empty (root) path. */
              rule->len = 0;
              rule->path = NULL;
              return SVN_NO_ERROR;
            }

          /* A path with two consecutive slashes is not canonical. */
          return svn_error_createf(
              SVN_ERR_AUTHZ_INVALID_CONFIG,
              svn_error_create(SVN_ERR_AUTHZ_INVALID_CONFIG, NULL,
                               _("Found empty name in authz rule path")),
              _("Non-canonical path '%s' in authz rule [%s]"),
              path, section);
        }

      /* A path with . or .. segments is not canonical. */
      if (*start == '.'
          && (pattern_len == 1
              || (pattern_len == 2 && start[1] == '.')))
        return svn_error_createf(
            SVN_ERR_AUTHZ_INVALID_CONFIG,
            (end == start + 1
             ? svn_error_create(SVN_ERR_AUTHZ_INVALID_CONFIG, NULL,
                                _("Found '.' in authz rule path"))
             : svn_error_create(SVN_ERR_AUTHZ_INVALID_CONFIG, NULL,
                                _("Found '..' in authz rule path"))),
            _("Non-canonical path '%s' in authz rule [%s]"),
            path, section);

      /* Make space for the current segment. */
      ++nseg;
      svn_membuf__resize(&cb->rule_path_buffer, nseg * sizeof(*segment));
      segment = cb->rule_path_buffer.data;
      segment += (nseg - 1);

      if (!glob)
        {
          /* Trivial case: this is not a glob rule, so every segment
             is a literal match. */
          segment->kind = authz_rule_literal;
          intern_pattern(cb, &segment->pattern, start, pattern_len);
          continue;
        }

      /* Copy the segment into the temporary buffer. */
      svn_stringbuf_setempty(pattern);
      svn_stringbuf_appendbytes(pattern, start, pattern_len);

      if (0 == apr_fnmatch_test(pattern->data))
        {
          /* It's a literal match after all. */
          segment->kind = authz_rule_literal;
          unescape_in_place(pattern);
          intern_pattern(cb, &segment->pattern, pattern->data, pattern->len);
          continue;
        }

      if (*pattern->data == '*')
        {
          if (pattern->len == 1
              || (pattern->len == 2 && pattern->data[1] == '*'))
            {
              /* Process * and **, applying normalization as per
                 https://wiki.apache.org/subversion/AuthzImprovements. */

              authz_rule_segment_t *const prev =
                (nseg > 1 ? segment - 1 : NULL);

              if (pattern_len == 1)
                {
                  /* This is a *. Replace **|* with *|**. */
                  if (prev && prev->kind == authz_rule_any_recursive)
                    {
                      prev->kind = authz_rule_any_segment;
                      segment->kind = authz_rule_any_recursive;
                    }
                  else
                    segment->kind = authz_rule_any_segment;
                }
              else
                {
                  /* This is a **. Replace **|** with a single **. */
                  if (prev && prev->kind == authz_rule_any_recursive)
                    {
                      /* Simply drop the redundant new segment. */
                      --nseg;
                      continue;
                    }
                  else
                    segment->kind = authz_rule_any_recursive;
                }

              segment->pattern.data = interned_empty_string;
              segment->pattern.len = 0;
              continue;
            }

          /* Maybe it's a suffix match? */
          if (0 == apr_fnmatch_test(pattern->data + 1))
            {
              svn_stringbuf_leftchop(pattern, 1);
              segment->kind = authz_rule_suffix;
              unescape_in_place(pattern);
              svn_authz__reverse_string(pattern->data, pattern->len);
              intern_pattern(cb, &segment->pattern,
                             pattern->data, pattern->len);
              continue;
            }
        }

      if (pattern->data[pattern->len - 1] == '*')
        {
          /* Might be a prefix match. Note that because of the
             previous test, we already know that the pattern is longer
             than one character. */
          if (pattern->data[pattern->len - 2] != '\\')
            {
              /* OK, the * wasn't  escaped. Chop off the wildcard. */
              svn_stringbuf_chop(pattern, 1);
              if (0 == apr_fnmatch_test(pattern->data))
                {
                  segment->kind = authz_rule_prefix;
                  unescape_in_place(pattern);
                  intern_pattern(cb, &segment->pattern,
                                 pattern->data, pattern->len);
                  continue;
                }

              /* Restore the wildcard since it was not a prefix match. */
              svn_stringbuf_appendbyte(pattern, '*');
            }
        }

      /* It's a generic fnmatch pattern. */
      segment->kind = authz_rule_fnmatch;
      intern_pattern(cb, &segment->pattern, pattern->data, pattern->len);
    }

  SVN_ERR_ASSERT(nseg > 0);

  /* Copy the temporary segments array into the result pool. */
  {
    const apr_size_t path_size = nseg * sizeof(*segment);
    SVN_ERR_ASSERT(path_size <= cb->rule_path_buffer.size);

    rule->len = nseg;
    rule->path = apr_palloc(cb->authz->pool, path_size);
    memcpy(rule->path, cb->rule_path_buffer.data, path_size);
  }

  return SVN_NO_ERROR;
}


/* Check that the parsed RULE is unique within the authz file.
   With the introduction of wildcards, just looking at the SECTION
   names is not sufficient to determine uniqueness.
   Use pools and buffers from CB to do the obvious thing. */
static svn_error_t *
check_unique_rule(ctor_baton_t *cb,
                  const authz_rule_t *rule,
                  const char *section)
{
  svn_stringbuf_t *const buf = cb->rule_string_buffer;
  const char *exists;
  int i;

  /* Construct the key for this rule */
  svn_stringbuf_setempty(buf);
  svn_stringbuf_appendcstr(buf, rule->repos);
  svn_stringbuf_appendbyte(buf, '\n');

  for (i = 0; i < rule->len; ++i)
    {
      authz_rule_segment_t *const seg = &rule->path[i];
      svn_stringbuf_appendbyte(buf, '@' + seg->kind);
      svn_stringbuf_appendbytes(buf, seg->pattern.data, seg->pattern.len);
      svn_stringbuf_appendbyte(buf, '\n');
    }

  /* Check if the section exists. */
  exists = apr_hash_get(cb->parsed_rules, buf->data, buf->len);
  if (exists)
    return svn_error_createf(
        SVN_ERR_AUTHZ_INVALID_CONFIG, NULL,
        _("Section [%s] describes the same rule as section [%s]"),
        section, exists);

  /* Insert the rule into the known rules set. */
  apr_hash_set(cb->parsed_rules,
               apr_pstrmemdup(cb->parser_pool, buf->data, buf->len),
               buf->len,
               apr_pstrdup(cb->parser_pool, section));

  return SVN_NO_ERROR;
}


/* Constructor callback: Starts a rule or [aliases] section. */
static svn_error_t *
rules_open_section(void *baton, svn_stringbuf_t *section)
{
  ctor_baton_t *const cb = baton;
  const char *rule = section->data;
  apr_size_t rule_len = section->len;
  svn_boolean_t glob;
  const char *endp;
  parsed_acl_t acl;

  SVN_ERR(check_open_section(cb, section));

  /* Parse rule property tokens. */
  if (*rule != ':')
    glob = FALSE;
  else
    {
      /* This must be a wildcard rule. */
      apr_size_t token_len;

      ++rule; --rule_len;
      endp = memchr(rule, ':', rule_len);
      if (!endp)
        return svn_error_createf(
            SVN_ERR_AUTHZ_INVALID_CONFIG, NULL,
            _("Empty repository name in authz rule [%s]"),
            section->data);

      /* Note: the size of glob_rule_token includes the NUL terminator. */
      token_len = endp - rule;
      if (token_len != sizeof(glob_rule_token) - 1
          || memcmp(rule, glob_rule_token, token_len))
        return svn_error_createf(
            SVN_ERR_AUTHZ_INVALID_CONFIG, NULL,
            _("Invalid type token '%s' in authz rule [%s]"),
            apr_pstrmemdup(cb->parser_pool, rule, token_len),
            section->data);

      glob = TRUE;
      rule = endp + 1;
      rule_len -= token_len + 1;
    }

  /* Parse the repository name. */
  endp = (*rule == '/' ? NULL : memchr(rule, ':', rule_len));
  if (!endp)
    acl.acl.rule.repos = interned_empty_string;
  else
    {
      const apr_size_t repos_len = endp - rule;

      /* The rule contains a repository name. */
      if (0 == repos_len)
        return svn_error_createf(
            SVN_ERR_AUTHZ_INVALID_CONFIG, NULL,
            _("Empty repository name in authz rule [%s]"),
            section->data);

      acl.acl.rule.repos = intern_string(cb, rule, repos_len);
      rule = endp + 1;
      rule_len -= repos_len + 1;
    }

  /* Parse the actual rule. */
  if (*rule == '/')
    {
      SVN_ERR(parse_rule_path(&acl.acl.rule, cb, glob, rule, rule_len,
                              section->data));
      SVN_ERR(check_unique_rule(cb, &acl.acl.rule, section->data));
    }
  else if (0 == strcmp(section->data, aliases_section))
    {
      cb->in_aliases = TRUE;
      return SVN_NO_ERROR;
    }
  else
    {
      /* This must be the [groups] section. */
      return groups_open_section(cb, section);
    }

  acl.acl.sequence_number = cb->parsed_acls->nelts;
  acl.acl.anon_access = authz_access_none;
  acl.acl.has_anon_access = FALSE;
  acl.acl.authn_access = authz_access_none;
  acl.acl.has_authn_access = FALSE;
  acl.acl.neg_access = authz_access_none;
  acl.acl.has_neg_access = FALSE;
  acl.acl.user_access = NULL;

  acl.aces = svn_hash__make(cb->parser_pool);
  acl.alias_aces = svn_hash__make(cb->parser_pool);

  cb->current_acl = &APR_ARRAY_PUSH(cb->parsed_acls, parsed_acl_t);
  *cb->current_acl = acl;
  return SVN_NO_ERROR;
}


/* Parses an alias declaration. The definition (username) of the
   alias will always be interned. */
static svn_error_t *
add_alias_definition(ctor_baton_t *cb,
                     svn_stringbuf_t *option, svn_stringbuf_t *value)
{
  const char *alias;
  apr_size_t alias_len;
  const char *user;

  if (strchr("@$&*~", *option->data))
    return svn_error_createf(
        SVN_ERR_AUTHZ_INVALID_CONFIG, NULL,
        _("Alias name '%s' may not begin with '%c'"),
        option->data, *option->data);

  /* Decorate the name to make lookups consistent. */
  alias = apr_pstrcat(cb->parser_pool, "&", option->data, SVN_VA_NULL);
  alias_len = option->len + 1;
  if (apr_hash_get(cb->parsed_aliases, alias, alias_len))
    return svn_error_createf(
        SVN_ERR_AUTHZ_INVALID_CONFIG, NULL,
        _("Can't override definition of alias '%s'"),
        alias);

  user = intern_string(cb, value->data, value->len);
  apr_hash_set(cb->parsed_aliases, alias, alias_len, user);

  /* Prepare the global rights struct for this user. */
  prepare_global_rights(cb, user);
  return SVN_NO_ERROR;
}

/* Parses an access entry. Groups and users in access entry names will
   always be interned, aliases will never be. */
static svn_error_t *
add_access_entry(ctor_baton_t *cb, svn_stringbuf_t *section,
                 svn_stringbuf_t *option, svn_stringbuf_t *value)
{
  parsed_acl_t *const acl = cb->current_acl;
  const char *name = option->data;
  apr_size_t name_len = option->len;
  const svn_boolean_t inverted = (*name == '~');
  svn_boolean_t anonymous = FALSE;
  svn_boolean_t authenticated = FALSE;
  authz_access_t access = authz_access_none;
  authz_ace_t *ace;
  int i;

  SVN_ERR_ASSERT(acl != NULL);

  if (inverted)
    {
      ++name;
      --name_len;
    }

  /* Determine the access entry type. */
  switch (*name)
    {
    case '~':
      return svn_error_createf(
          SVN_ERR_AUTHZ_INVALID_CONFIG, NULL,
          _("Access entry '%s' has more than one inversion;"
            " double negatives are not permitted"),
          option->data);
      break;

    case '*':
      if (name_len != 1)
        return svn_error_createf(
            SVN_ERR_AUTHZ_INVALID_CONFIG, NULL,
            _("Access entry '%s' is not valid;"
              " it must be a single '*'"),
            option->data);

      if (inverted)
        return svn_error_createf(
            SVN_ERR_AUTHZ_INVALID_CONFIG, NULL,
            _("Access entry '~*' will never match"));

      anonymous = TRUE;
      authenticated = TRUE;
      break;

    case '$':
      if (0 == strcmp(name, anon_access_token))
        {
          if (inverted)
            authenticated = TRUE;
          else
            anonymous = TRUE;
        }
      else if (0 == strcmp(name, authn_access_token))
        {
          if (inverted)
            anonymous = TRUE;
          else
            authenticated = TRUE;
        }
      else
        return svn_error_createf(
            SVN_ERR_AUTHZ_INVALID_CONFIG, NULL,
            _("Access entry token '%s' is not valid;"
              " should be '%s' or '%s'"),
            option->data, anon_access_token, authn_access_token);
      break;

    default:
      /* A username, group name or alias. */;
    }

  /* Parse the access rights. */
  for (i = 0; i < value->len; ++i)
    {
      const char access_code = value->data[i];
      switch (access_code)
        {
        case 'r':
          access |= authz_access_read_flag;
          break;

        case 'w':
          access |= authz_access_write_flag;
          break;

        default:
          if (!svn_ctype_isspace(access_code))
            return svn_error_createf(
                SVN_ERR_AUTHZ_INVALID_CONFIG, NULL,
                _("The access mode '%c' in access entry '%s'"
                  " of rule [%s] is not valid"),
                access_code, option->data, section->data);
      }
    }

  /* We do not support write-only access. */
  if ((access & authz_access_write_flag) && !(access & authz_access_read_flag))
    return svn_error_createf(
        SVN_ERR_AUTHZ_INVALID_CONFIG, NULL,
        _("Write-only access entry '%s' of rule [%s] is not valid"),
        option->data, section->data);

  /* Update the parsed ACL with this access entry. */
  if (anonymous || authenticated)
    {
      if (anonymous)
        {
          acl->acl.has_anon_access = TRUE;
          acl->acl.anon_access |= access;
        }
      if (authenticated)
        {
          acl->acl.has_authn_access = TRUE;
          acl->acl.authn_access |= access;
        }
    }
  else
    {
      /* The inversion tag must be part of the key in the hash
         table, otherwise we can't tell regular and inverted
         entries appart. */
      const char *key = (inverted ? name - 1 : name);
      const apr_size_t key_len = (inverted ? name_len + 1 : name_len);
      const svn_boolean_t aliased = (*name == '&');
      apr_hash_t *aces = (aliased ? acl->alias_aces : acl->aces);

      ace = apr_hash_get(aces, key, key_len);
      if (ace)
        ace->access |= access;
      else
        {
          ace = apr_palloc(cb->parser_pool, sizeof(*ace));
          ace->name = (aliased
                       ? apr_pstrmemdup(cb->parser_pool, name, name_len)
                       : intern_string(cb, name, name_len));
          ace->members = NULL;
          ace->inverted = inverted;
          ace->access = access;

          key = (inverted
                 ? apr_pstrmemdup(cb->parser_pool, key, key_len)
                 : ace->name);
          apr_hash_set(aces, key, key_len, ace);

          /* Prepare the global rights struct for this user. */
          if (!aliased && *ace->name != '@')
            prepare_global_rights(cb, ace->name);
        }

      /* Propagate rights for inverted selectors to the global rights, otherwise
         an access check can bail out early. See: SVN-4793 */
      if (inverted)
        {
          acl->acl.has_neg_access = TRUE;
          acl->acl.neg_access |= access;
        }
    }

  return SVN_NO_ERROR;
}

/* Constructor callback: Parse a rule, alias or group delcaration. */
static svn_error_t *
rules_add_value(void *baton, svn_stringbuf_t *section,
                svn_stringbuf_t *option, svn_stringbuf_t *value)
{
  ctor_baton_t *const cb = baton;

  if (cb->in_groups)
    return groups_add_value(baton, section, option, value);

  if (cb->in_aliases)
    return add_alias_definition(cb, option, value);

  return add_access_entry(cb, section, option, value);
}


/* Constructor callback: Close a section. */
static svn_error_t *
close_section(void *baton, svn_stringbuf_t *section)
{
  ctor_baton_t *const cb = baton;

  SVN_ERR_ASSERT(0 == strcmp(cb->section, section->data));
  cb->section = NULL;
  cb->current_acl = NULL;
  cb->in_groups = FALSE;
  cb->in_aliases = FALSE;
  return SVN_NO_ERROR;
}


/* Add a user to GROUP.
   GROUP is never internalized, but USER always is.
   Adding a NULL user will create an empty group, if it doesn't exist. */
static void
add_to_group(ctor_baton_t *cb, const char *group, const char *user)
{
  apr_hash_t *members = svn_hash_gets(cb->expanded_groups, group);
  if (!members)
    {
      group = intern_string(cb, group, -1);
      members = svn_hash__make(cb->authz->pool);
      svn_hash_sets(cb->expanded_groups, group, members);
    }
  if (user)
    svn_hash_sets(members, user, interned_empty_string);
}


/* Hash iterator for expanding group definitions.
   WARNING: This function is recursive! */
static svn_error_t *
expand_group_callback(void *baton,
                      const void *key,
                      apr_ssize_t klen,
                      void *value,
                      apr_pool_t *scratch_pool)
{
  ctor_baton_t *const cb = baton;
  const char *const group = key;
  apr_array_header_t *members = value;
  int i;

  if (0 == members->nelts)
    {
      /* Create the group with no members. */
      add_to_group(cb, group, NULL);
      return SVN_NO_ERROR;
    }

  for (i = 0; i < members->nelts; ++i)
    {
      const char *member = APR_ARRAY_IDX(members, i, const char*);
      if (0 == strcmp(member, group))
            return svn_error_createf(SVN_ERR_AUTHZ_INVALID_CONFIG, NULL,
                                     _("Recursive definition of group '%s'"),
                                     group);

      if (*member == '&')
        {
          /* Add expanded alias to the group.
             N.B.: the user name is already internalized. */
          const char *user = svn_hash_gets(cb->parsed_aliases, member);
          if (!user)
            return svn_error_createf(
                SVN_ERR_AUTHZ_INVALID_CONFIG, NULL,
                _("Alias '%s' was never defined"),
                member);

          add_to_group(cb, group, user);
        }
      else if (*member != '@')
        {
          /* Add the member to the group. */
          const char *user = intern_string(cb, member, -1);
          add_to_group(cb, group, user);

          /* Prepare the global rights struct for this user. */
          prepare_global_rights(cb, user);
        }
      else
        {
          /* Recursively expand the group membership */
          apr_array_header_t *member_members
            = svn_hash_gets(cb->parsed_groups, member);
          if (!member_members)
            return svn_error_createf(
                SVN_ERR_AUTHZ_INVALID_CONFIG, NULL,
                _("Undefined group '%s'"),
                member);
          SVN_ERR(expand_group_callback(cb, key, klen,
                                        member_members, scratch_pool));
        }
    }
  return SVN_NO_ERROR;
}


/* Hash iteration baton for merge_alias_ace. */
typedef struct merge_alias_baton_t
{
  apr_hash_t *aces;
  ctor_baton_t *cb;
} merge_alias_baton_t;

/* Hash iterator for expanding and mergina alias-based ACEs
   into the user/group-based ACEs. */
static svn_error_t *
merge_alias_ace(void *baton,
                const void *key,
                apr_ssize_t klen,
                void *value,
                apr_pool_t *scratch_pool)
{
  merge_alias_baton_t *const mab = baton;
  authz_ace_t *aliased_ace = value;
  const char *alias = aliased_ace->name;
  const char *unaliased_key;
  const char *user;
  authz_ace_t *ace;

  user = svn_hash_gets(mab->cb->parsed_aliases, alias);
  if (!user)
    return svn_error_createf(
        SVN_ERR_AUTHZ_INVALID_CONFIG, NULL,
        _("Alias '%s' was never defined"),
        alias);

  /* N.B.: The user name is always internalized,
     but the inverted key may not be. */
  if (!aliased_ace->inverted)
    unaliased_key = user;
  else
    {
      unaliased_key = apr_pstrcat(mab->cb->parser_pool,
                                  "~", user, SVN_VA_NULL);
      unaliased_key = intern_string(mab->cb, unaliased_key, -1);
    }

  ace = svn_hash_gets(mab->aces, unaliased_key);
  if (!ace)
    {
      aliased_ace->name = user;
      svn_hash_sets(mab->aces, unaliased_key, aliased_ace);
    }
  else
    {
      SVN_ERR_ASSERT(!ace->inverted == !aliased_ace->inverted);
      ace->access |= aliased_ace->access;
    }

  return SVN_NO_ERROR;
}


/* Hash iteration baton for array_insert_ace. */
typedef struct insert_ace_baton_t
{
  apr_array_header_t *ace_array;
  ctor_baton_t *cb;
} insert_ace_baton_t;

/* Hash iterator, inserts an ACE into the ACLs array. */
static svn_error_t *
array_insert_ace(void *baton,
                 const void *key,
                 apr_ssize_t klen,
                 void *value,
                 apr_pool_t *scratch_pool)
{
  insert_ace_baton_t *iab = baton;
  authz_ace_t *ace = value;

  /* Add group membership info to the ACE. */
  if (*ace->name == '@')
    {
      SVN_ERR_ASSERT(ace->members == NULL);
      ace->members = svn_hash_gets(iab->cb->expanded_groups, ace->name);
      if (!ace->members)
        {
          return svn_error_createf(
              SVN_ERR_AUTHZ_INVALID_CONFIG, NULL,
              _("Access entry refers to undefined group '%s'"),
              ace->name);
        }
      else if (0 == apr_hash_count(ace->members))
        {
          /* An ACE for an empty group has no effect, so ignore it. */
          SVN_AUTHZ_PARSE_WARN(
              iab->cb,
              svn_error_createf(
                  SVN_ERR_AUTHZ_INVALID_CONFIG, NULL,
                  _("Ignoring access entry for empty group '%s'"),
                  ace->name),
              scratch_pool);
          return SVN_NO_ERROR;
        }
    }

  APR_ARRAY_PUSH(iab->ace_array, authz_ace_t) = *ace;
  return SVN_NO_ERROR;
}


/* Update accumulated RIGHTS from ACCESS. */
static void
update_rights(authz_rights_t *rights,
              authz_access_t access)
{
  rights->min_access &= access;
  rights->max_access |= access;
}


/* Update a global RIGHTS based on REPOS and ACCESS. */
static void
update_global_rights(authz_global_rights_t *gr,
                     const char *repos,
                     authz_access_t access)
{
  update_rights(&gr->all_repos_rights, access);
  if (0 == strcmp(repos, AUTHZ_ANY_REPOSITORY))
    update_rights(&gr->any_repos_rights, access);
  else
    {
      authz_rights_t *rights = svn_hash_gets(gr->per_repos_rights, repos);
      if (rights)
        update_rights(rights, access);
      else
        {
          rights = apr_palloc(apr_hash_pool_get(gr->per_repos_rights),
                              sizeof(*rights));
          init_rights(rights);
          update_rights(rights, access);
          svn_hash_sets(gr->per_repos_rights, repos, rights);
        }
    }
}


/* Hash iterator to update global per-user rights from an ACL. */
static svn_error_t *
update_user_rights(void *baton,
                   const void *key,
                   apr_ssize_t klen,
                   void *value,
                   apr_pool_t *scratch_pool)
{
  const authz_acl_t *const acl = baton;
  const char *const user = key;
  authz_global_rights_t *const gr = value;
  authz_access_t access;
  svn_boolean_t has_access =
    svn_authz__get_acl_access(&access, acl, user, acl->rule.repos);

  if (has_access)
    update_global_rights(gr, acl->rule.repos, access);
  return SVN_NO_ERROR;
}


/* List iterator, expands/merges a parsed ACL into its final form and
   appends it to the authz info's ACL array. */
static svn_error_t *
expand_acl_callback(void *baton,
                    void *item,
                    apr_pool_t *scratch_pool)
{
  ctor_baton_t *const cb = baton;
  parsed_acl_t *const pacl = item;
  authz_acl_t *const acl = &pacl->acl;

  /* Expand and merge the aliased ACEs. */
  if (apr_hash_count(pacl->alias_aces))
    {
      merge_alias_baton_t mab;
      mab.aces = pacl->aces;
      mab.cb = cb;
      SVN_ERR(svn_iter_apr_hash(NULL, pacl->alias_aces,
                                merge_alias_ace, &mab, scratch_pool));
    }

  /* Make an array from the merged hashes. */
  acl->user_access =
    apr_array_make(cb->authz->pool, apr_hash_count(pacl->aces),
                   sizeof(authz_ace_t));
  {
    insert_ace_baton_t iab;
    iab.ace_array = acl->user_access;
    iab.cb = cb;
    SVN_ERR(svn_iter_apr_hash(NULL, pacl->aces,
                              array_insert_ace, &iab, scratch_pool));
  }

  /* Store the completed ACL into authz. */
  APR_ARRAY_PUSH(cb->authz->acls, authz_acl_t) = *acl;

  /* Update global access rights for this ACL. */
  if (acl->has_anon_access)
    {
      cb->authz->has_anon_rights = TRUE;
      update_global_rights(&cb->authz->anon_rights,
                           acl->rule.repos, acl->anon_access);
    }
  if (acl->has_authn_access)
    {
      cb->authz->has_authn_rights = TRUE;
      update_global_rights(&cb->authz->authn_rights,
                           acl->rule.repos, acl->authn_access);
    }
  if (acl->has_neg_access)
    {
      cb->authz->has_neg_rights = TRUE;
      update_global_rights(&cb->authz->neg_rights,
                           acl->rule.repos, acl->neg_access);
    }
  SVN_ERR(svn_iter_apr_hash(NULL, cb->authz->user_rights,
                            update_user_rights, acl, scratch_pool));
  return SVN_NO_ERROR;
}


/* Compare two ACLs in rule lexical order, then repository order, then
   order of definition. This ensures that our default ACL is always
   first in the sorted array. */
static int
compare_parsed_acls(const void *va, const void *vb)
{
  const parsed_acl_t *const a = va;
  const parsed_acl_t *const b = vb;

  int cmp = svn_authz__compare_rules(&a->acl.rule, &b->acl.rule);
  if (cmp == 0)
    cmp = a->acl.sequence_number - b->acl.sequence_number;
  return cmp;
}


svn_error_t *
svn_authz__parse(authz_full_t **authz,
                 svn_stream_t *rules,
                 svn_stream_t *groups,
                 svn_repos_authz_warning_func_t warning_func,
                 void *warning_baton,
                 apr_pool_t *result_pool,
                 apr_pool_t *scratch_pool)
{
  ctor_baton_t *const cb = create_ctor_baton(warning_func, warning_baton,
                                             result_pool, scratch_pool);

  /*
   * Pass 1: Parse the authz file.
   */
  SVN_ERR(svn_config__parse_stream(rules,
                                   svn_config__constructor_create(
                                       rules_open_section,
                                       close_section,
                                       rules_add_value,
                                       cb->parser_pool),
                                   cb, cb->parser_pool));

  /*
   * Pass 1.6487: Parse the global groups file.
   */
  if (groups)
    {
      /* Check that the authz file did not contain any groups. */
      if (0 != apr_hash_count(cb->parsed_groups))
          return svn_error_create(SVN_ERR_AUTHZ_INVALID_CONFIG, NULL,
                                  ("Authz file cannot contain any groups"
                                   " when global groups are being used."));

      apr_hash_clear(cb->sections);
      cb->parsing_groups = TRUE;
      SVN_ERR(svn_config__parse_stream(groups,
                                       svn_config__constructor_create(
                                           groups_open_section,
                                           close_section,
                                           groups_add_value,
                                           cb->parser_pool),
                                       cb, cb->parser_pool));
    }

  /*
   * Pass 2: Expand groups and construct the final svn_authz_t.
   */
  cb->expanded_groups = svn_hash__make(cb->parser_pool);
  SVN_ERR(svn_iter_apr_hash(NULL, cb->parsed_groups,
                            expand_group_callback, cb, cb->parser_pool));


  /* Sort the parsed ACLs in rule lexical order and pop off the
     default global ACL iff an equivalent ACL was defined in the authz
     file. */
  if (cb->parsed_acls->nelts > 1)
    {
      parsed_acl_t *defacl;
      parsed_acl_t *nxtacl;

      svn_sort__array(cb->parsed_acls, compare_parsed_acls);
      defacl = &APR_ARRAY_IDX(cb->parsed_acls, 0, parsed_acl_t);
      nxtacl = &APR_ARRAY_IDX(cb->parsed_acls, 1, parsed_acl_t);

      /* If the first ACL is not our default thingamajig, there's a
         bug in our comparator. */
      SVN_ERR_ASSERT(
          defacl->acl.sequence_number == 0 && defacl->acl.rule.len == 0
          && 0 == strcmp(defacl->acl.rule.repos, AUTHZ_ANY_REPOSITORY));

      /* Pop the default ACL off the array if another equivalent
         exists, after merging the default rights. */
      if (0 == svn_authz__compare_rules(&defacl->acl.rule, &nxtacl->acl.rule))
        {
          nxtacl->acl.has_anon_access = TRUE;
          nxtacl->acl.has_authn_access = TRUE;
          cb->parsed_acls->elts = (char*)(nxtacl);
          --cb->parsed_acls->nelts;
        }
    }

  cb->authz->acls = apr_array_make(cb->authz->pool, cb->parsed_acls->nelts,
                                   sizeof(authz_acl_t));
  SVN_ERR(svn_iter_apr_array(NULL, cb->parsed_acls,
                             expand_acl_callback, cb, cb->parser_pool));

  *authz = cb->authz;
  apr_pool_destroy(cb->parser_pool);
  return SVN_NO_ERROR;
}


void
svn_authz__reverse_string(char *string, apr_size_t len)
{
  char *left = string;
  char *right = string + len - 1;
  for (; left < right; ++left, --right)
    {
      char c = *left;
      *left = *right;
      *right = c;
    }
}


int
svn_authz__compare_paths(const authz_rule_t *a, const authz_rule_t *b)
{
  const int min_len = (a->len > b->len ? b->len : a->len);
  int i;

  for (i = 0; i < min_len; ++i)
    {
      int cmp = a->path[i].kind - b->path[i].kind;
      if (0 == cmp)
        {
          const char *const aseg = a->path[i].pattern.data;
          const char *const bseg = b->path[i].pattern.data;

          /* Exploit the fact that segment patterns are interned. */
          if (aseg != bseg)
            cmp = strcmp(aseg, bseg);
          else
            cmp = 0;
        }
      if (0 != cmp)
        return cmp;
    }

  /* Sort shorter rules first. */
  if (a->len != b->len)
    return a->len - b->len;

  return 0;
}

int
svn_authz__compare_rules(const authz_rule_t *a, const authz_rule_t *b)
{
  int diff = svn_authz__compare_paths(a, b);
  if (diff)
    return diff;

  /* Repository names are interned, too. */
  if (a->repos != b->repos)
    return strcmp(a->repos, b->repos);

  return 0;
}