File: mod_vroot.c

package info (click to toggle)
proftpd-mod-vroot 0.9.4-2
  • links: PTS, VCS
  • area: main
  • in suites: buster, sid
  • size: 616 kB
  • sloc: perl: 11,003; ansic: 1,234; makefile: 17
file content (1867 lines) | stat: -rw-r--r-- 47,914 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
/*
 * ProFTPD: mod_vroot -- a module implementing a virtual chroot capability
 *                       via the FSIO API
 *
 * Copyright (c) 2002-2015 TJ Saunders
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307, USA.
 *
 * As a special exemption, TJ Saunders and other respective copyright holders
 * give permission to link this program with OpenSSL, and distribute the
 * resulting executable, without including the source code for OpenSSL in the
 * source distribution.
 *
 * This is mod_vroot, contrib software for proftpd 1.3.x and above.
 * For more information contact TJ Saunders <tj@castaglia.org>.
 */

#include "conf.h"
#include "privs.h"

#define MOD_VROOT_VERSION 	"mod_vroot/0.9.4"

/* Make sure the version of proftpd is as necessary. */
#if PROFTPD_VERSION_NUMBER < 0x0001030602
# error "ProFTPD 1.3.6rc2 or later required"
#endif

static const char *vroot_log = NULL;
static int vroot_logfd = -1;

static char vroot_base[PR_TUNABLE_PATH_MAX + 1];
static size_t vroot_baselen = 0;
static unsigned char vroot_engine = FALSE;

static pool *vroot_alias_pool = NULL;
static pr_table_t *vroot_aliastab = NULL;

static pool *vroot_dir_pool = NULL;
static pr_table_t *vroot_dirtab = NULL;

#if PROFTPD_VERSION_NUMBER >= 0x0001030407
static int vroot_use_mkdtemp = FALSE;
#endif /* ProFTPD 1.3.4c or later */

static unsigned int vroot_opts = 0;
#define	VROOT_OPT_ALLOW_SYMLINKS	0x0001

/* vroot_realpath() flags */
#define VROOT_REALPATH_FL_ABS_PATH	0x001

/* vroot_lookup_path() flags */
#define VROOT_LOOKUP_FL_NO_ALIASES	0x0001

static const char *trace_channel = "vroot";

static int vroot_is_alias(const char *);

/* Support routines note: some of these support functions are borrowed from
 * pure-ftpd.
 */

static void strmove(register char *dst, register const char *src) {
  if (dst == NULL ||
      src == NULL) {
    return;
  }

  while (*src != 0) {
    *dst++ = *src++;
  }

  *dst = 0;
}

static void vroot_clean_path(char *path) {
  char *p = NULL;

  if (path == NULL ||
      *path == 0) {
      return;
  }

  while ((p = strstr(path, "//")) != NULL) {
    strmove(p, p + 1);
  }

  while ((p = strstr(path, "/./")) != NULL) {
    strmove(p, p + 2);
  }

  while (strncmp(path, "../", 3) == 0) {
    path += 3;
  }

  p = strstr(path, "/../");
  if (p != NULL) {
    if (p == path) {
      while (strncmp(path, "/../", 4) == 0) {
        strmove(path, path + 3);
      }

      p = strstr(path, "/../");
    }

    while (p != NULL) {
      char *next_elem = p + 4;

      if (p != path &&
          *p == '/') {
        p--;
      }

      while (p != path &&
             *p != '/') {
        p--;
      }

      if (*p == '/') {
        p++;
      }

      strmove(p, next_elem);
      p = strstr(path, "/../");
    }
  }

  p = path;

  if (*p == '.') {
    p++;

    if (*p == '\0') {
      return;
    }

    if (*p == '/') {
      while (*p == '/') {
        p++;
      }

      strmove(path, p);
    }
  }

  if (*p == '\0') {
    return;
  }

  p = path + strlen(path) - 1;
  if (*p != '.' ||
      p == path) {
    return;
  }

  p--;
  if (*p == '/' ||
      p == path) {
    p[1] = '\0';
    return;
  }

  if (*p != '.' ||
      p == path) {
    return;
  }

  p--;
  if (*p != '/') {
    return;
  }

  *p = '\0';
  p = strrchr(path, '/');
  if (p == NULL) {
    *path = '/';
    path[1] = '\0';
    return;
  }

  p[1] = '\0';
}

static char *vroot_realpath(pool *p, const char *path, int flags) {
  char *real_path = NULL;
  size_t real_pathlen;

  if (flags & VROOT_REALPATH_FL_ABS_PATH) {
    /* If not an absolute path, prepend the current location. */
    if (*path != '/') {
      real_path = pdircat(p, pr_fs_getvwd(), path, NULL);

    } else {
      real_path = pstrdup(p, path);
    }

  } else {
    real_path = pstrdup(p, path);
  }

  vroot_clean_path(real_path);

  /* If the given path ends in a slash, remove it.  The handling of
   * VRootAliases is sensitive to such things.
   */
  real_pathlen = strlen(real_path);
  if (real_pathlen > 1 &&
      real_path[real_pathlen-1] == '/') {
    real_path[real_pathlen-1] = '\0';
    real_pathlen--;
  }

  return real_path;
}

static int vroot_lookup_path(pool *p, char *path, size_t pathlen,
    const char *dir, int flags, char **alias_path) {
  char buf[PR_TUNABLE_PATH_MAX + 1], *bufp = NULL;

  memset(buf, '\0', sizeof(buf));
  memset(path, '\0', pathlen);

  if (strcmp(dir, ".") != 0) {
    sstrncpy(buf, dir, sizeof(buf));

  } else {
    sstrncpy(buf, pr_fs_getcwd(), sizeof(buf));
  }

  vroot_clean_path(buf);

  bufp = buf;

  if (strncmp(bufp, vroot_base, vroot_baselen) == 0) {
    bufp += vroot_baselen;
  }

loop:
  pr_signals_handle();

  if (bufp[0] == '.' &&
      bufp[1] == '.' &&
      (bufp[2] == '\0' ||
       bufp[2] == '/')) {
    char *tmp = NULL;

    tmp = strrchr(path, '/');
    if (tmp != NULL) {
      *tmp = '\0';

    } else {
      *path = '\0';
    }

    if (strncmp(path, vroot_base, vroot_baselen) == 0 ||
         path[vroot_baselen] != '/') {
      snprintf(path, pathlen, "%s/", vroot_base);
    }

    if (bufp[0] == '.' &&
        bufp[1] == '.' &&
        bufp[2] == '/') {
      bufp += 3;
      goto loop;
    }

  } else if (*bufp == '/') {
    snprintf(path, pathlen, "%s/", vroot_base);
    bufp += 1;
    goto loop;

  } else if (*bufp != '\0') {
    size_t buflen, tmplen;
    char *ptr = NULL;

    ptr = strstr(bufp, "..");
    if (ptr != NULL) {
      size_t ptrlen;

      /* We need to watch for path components/filenames which legitimately
       * contain two or more periods in addition to other characters.
       */

      ptrlen = strlen(ptr);
      if (ptrlen >= 3) {

        /* If this ".." occurrence is the start of the buffer AND the next
         * character after the ".." is a slash, then deny it.
         */
        if (ptr == bufp &&
            ptr[2] == '/') {
          errno = EPERM;
          return -1;
        }

        /* If this ".." occurrence is NOT the start of the buffer AND the
         * characters preceeding and following the ".." are slashes, then
         * deny it.
         */
        if (ptr != bufp &&
            ptr[-1] == '/' &&
            ptr[2] == '/') {
          errno = EPERM;
          return -1;
        }
      }
    }

    buflen = strlen(bufp) + 1;
    tmplen = strlen(path);

    if (tmplen + buflen >= pathlen) {
      errno = ENAMETOOLONG;
      return -1;
    }

    path[tmplen] = '/';
    memcpy(path + tmplen + 1, bufp, buflen);
  }

  /* Clean any unnecessary characters added by the above processing. */
  vroot_clean_path(path);

  if (!(flags & VROOT_LOOKUP_FL_NO_ALIASES)) {
    /* Check to see if this path is an alias; if so, return the real path. */
    if (vroot_aliastab != NULL) {
      char *start_ptr = NULL, *end_ptr = NULL;
      const char *src_path = NULL;

      /* buf is used here for storing the "suffix", to be appended later when
       * aliases are found.
       */
      bufp = buf;
      start_ptr = path;

      while (start_ptr != NULL) {
        char *ptr = NULL;

        pr_signals_handle();

        pr_trace_msg(trace_channel, 15, "checking for alias for '%s'",
          start_ptr);

        src_path = pr_table_get(vroot_aliastab, start_ptr, NULL);
        if (src_path != NULL) {
          pr_trace_msg(trace_channel, 15, "found '%s' for alias '%s'", src_path,
            start_ptr);

          /* If the caller provided a pointer for wanting to know the full
           * alias path (not the true path), then fill that pointer.
           */
          if (alias_path != NULL) {
            if (end_ptr != NULL) {
              *alias_path = pdircat(p, start_ptr, end_ptr + 1, NULL);

            } else {
              *alias_path = pstrdup(p, start_ptr);
            }

            pr_trace_msg(trace_channel, 19, "using alias path '%s' for '%s'",
              *alias_path, start_ptr);
          }

          sstrncpy(path, src_path, pathlen);

          if (end_ptr != NULL) {
            /* Now tack on our suffix from the scratchpad. */
            sstrcat(path, bufp, pathlen);
          }

          break;
        }

        ptr = strrchr(start_ptr, '/');

        if (end_ptr != NULL) {
          *end_ptr = '/';
        }

        if (ptr == NULL) {
          break;
        }

        /* If this is the start of the path, we're done. */
        if (ptr == start_ptr) {
          break;
        }

        /* Store the suffix in the buf scratchpad. */
        sstrncpy(buf, ptr, sizeof(buf));
        end_ptr = ptr;
        *end_ptr = '\0';
      }
    }
  }

  return 0;
}

static int vroot_is_alias(const char *path) {
  if (pr_table_get(vroot_aliastab, path, 0) != NULL) {
    return 0;
  }

  errno = ENOENT;
  return -1;
}

static int handle_vroot_alias(void) {
  config_rec *c;
  pool *tmp_pool = NULL;

  /* Handle any VRootAlias settings. */

  tmp_pool = make_sub_pool(session.pool);

  c = find_config(main_server->conf, CONF_PARAM, "VRootAlias", FALSE);
  while (c != NULL) {
    char src_path[PR_TUNABLE_PATH_MAX+1], dst_path[PR_TUNABLE_PATH_MAX+1];
    const char *ptr;

    pr_signals_handle();

    /* XXX Note that by using vroot_lookup_path(), we assume a POST_CMD
     * invocation.  Looks like VRootAlias might end up being incompatible
     * with VRootServerRoot.
     */

    memset(src_path, '\0', sizeof(src_path));
    ptr = c->argv[0];

    /* Check for any expandable variables. */
    ptr = path_subst_uservar(tmp_pool, &ptr);

    sstrncpy(src_path, ptr, sizeof(src_path)-1);
    vroot_clean_path(src_path);

    ptr = c->argv[1];

    /* Check for any expandable variables. */
    ptr = path_subst_uservar(tmp_pool, &ptr);

    ptr = dir_best_path(tmp_pool, ptr);
    vroot_lookup_path(NULL, dst_path, sizeof(dst_path)-1, ptr,
      VROOT_LOOKUP_FL_NO_ALIASES, NULL);

    if (vroot_alias_pool == NULL) {
      vroot_alias_pool = make_sub_pool(session.pool);
      pr_pool_tag(vroot_alias_pool, "VRoot Alias Pool");

      vroot_aliastab = pr_table_alloc(vroot_alias_pool, 0);
    }

    if (pr_table_add(vroot_aliastab, pstrdup(vroot_alias_pool, dst_path),
        pstrdup(vroot_alias_pool, src_path), 0) < 0) {

      /* Make a slightly better log message when there is an alias collision. */
      if (errno == EEXIST) {
        (void) pr_log_writefile(vroot_logfd, MOD_VROOT_VERSION,
          "VRootAlias already configured for '%s', ignoring bad alias",
          (char *) c->argv[1]);

      } else {
        (void) pr_log_writefile(vroot_logfd, MOD_VROOT_VERSION,
          "error stashing VRootAlias '%s': %s", dst_path, strerror(errno));
      }

    } else {
      (void) pr_log_writefile(vroot_logfd, MOD_VROOT_VERSION,
        "aliased '%s' to real path '%s'", dst_path, src_path);
    }

    c = find_config_next(c, c->next, CONF_PARAM, "VRootAlias", FALSE);
  }

  destroy_pool(tmp_pool);
  return 0;
}

/* FS callbacks
 */

static int vroot_stat(pr_fs_t *fs, const char *stat_path, struct stat *st) {
  int res;
  char vpath[PR_TUNABLE_PATH_MAX + 1], *path = NULL;
  pool *tmp_pool = NULL;

  if (session.curr_phase == LOG_CMD ||
      session.curr_phase == LOG_CMD_ERR ||
      (session.sf_flags & SF_ABORT) ||
      *vroot_base == '\0') {
    /* NOTE: once stackable FS modules are supported, have this fall through
     * to the next module in the stack.
     */
    return stat(stat_path, st);
  }

  tmp_pool = make_sub_pool(session.pool);
  path = vroot_realpath(tmp_pool, stat_path, 0);

  if (vroot_lookup_path(NULL, vpath, sizeof(vpath)-1, path, 0, NULL) < 0) {
    destroy_pool(tmp_pool);
    return -1;
  }

  res = stat(vpath, st);
  destroy_pool(tmp_pool);
  return res;
}

static int vroot_lstat(pr_fs_t *fs, const char *orig_path, struct stat *st) {
  int res;
  char vpath[PR_TUNABLE_PATH_MAX + 1], *path = NULL;
  size_t pathlen = 0;
  pool *tmp_pool = NULL;

  if (session.curr_phase == LOG_CMD ||
      session.curr_phase == LOG_CMD_ERR ||
      (session.sf_flags & SF_ABORT) ||
      *vroot_base == '\0') {
    /* NOTE: once stackable FS modules are supported, have this fall through
     * to the next module in the stack.
     */
    return lstat(orig_path, st);
  }

  tmp_pool = make_sub_pool(session.pool);

  path = pstrdup(tmp_pool, orig_path);
  vroot_clean_path(path);

  /* If the given path ends in a slash, remove it.  The handling of
   * VRootAliases is sensitive to such things.
   */
  pathlen = strlen(path);
  if (pathlen > 1 &&
      path[pathlen-1] == '/') {
    path[pathlen-1] = '\0';
    pathlen--;
  }

  if (vroot_lookup_path(NULL, vpath, sizeof(vpath)-1, path, 0, NULL) < 0) {
    destroy_pool(tmp_pool);
    return -1;
  }

  if ((vroot_opts & VROOT_OPT_ALLOW_SYMLINKS) ||
      vroot_is_alias(path) == 0) {
    res = lstat(vpath, st);
    if (res < 0) {
      destroy_pool(tmp_pool);
      return -1;
    }

    res = stat(vpath, st);
    destroy_pool(tmp_pool);
    return res;
  }

  res = lstat(vpath, st);
  destroy_pool(tmp_pool);
  return res;
}

static int vroot_rename(pr_fs_t *fs, const char *rnfm, const char *rnto) {
  int res;
  char vpath1[PR_TUNABLE_PATH_MAX + 1], vpath2[PR_TUNABLE_PATH_MAX + 1];

  if (session.curr_phase == LOG_CMD ||
      session.curr_phase == LOG_CMD_ERR ||
      (session.sf_flags & SF_ABORT) ||
      *vroot_base == '\0') {
    /* NOTE: once stackable FS modules are supported, have this fall through
     * to the next module in the stack.
     */
    res = rename(rnfm, rnto);
    return res;
  }

  if (vroot_lookup_path(NULL, vpath1, sizeof(vpath1)-1, rnfm, 0, NULL) < 0) {
    return -1;
  }

  if (vroot_lookup_path(NULL, vpath2, sizeof(vpath2)-1, rnto, 0, NULL) < 0) {
    return -1;
  }

  res = rename(vpath1, vpath2);
  return res;
}

static int vroot_unlink(pr_fs_t *fs, const char *path) {
  int res;
  char vpath[PR_TUNABLE_PATH_MAX + 1];

  if (vroot_base[0] == '\0') {
    /* NOTE: once stackable FS modules are supported, have this fall through
     * to the next module in the stack.
     */
    res = unlink(path);
    return res;
  }

  /* Do not allow deleting of aliased files/directories; the aliases may only
   * exist for this user/group.
   */
  if (vroot_lookup_path(NULL, vpath, sizeof(vpath)-1, path,
      VROOT_LOOKUP_FL_NO_ALIASES, NULL) < 0) {
    return -1;
  }

  if (vroot_is_alias(vpath) == 0) {
    (void) pr_log_writefile(vroot_logfd, MOD_VROOT_VERSION,
      "denying delete of '%s' because it is a VRootAlias", vpath);
    errno = EACCES;
    return -1;
  }

  if (vroot_lookup_path(NULL, vpath, sizeof(vpath)-1, path, 0, NULL) < 0) {
    return -1;
  }

  res = unlink(vpath);
  return res;
}

static int vroot_open(pr_fh_t *fh, const char *path, int flags) {
  int res;
  char vpath[PR_TUNABLE_PATH_MAX + 1];

  if (session.curr_phase == LOG_CMD ||
      session.curr_phase == LOG_CMD_ERR ||
      (session.sf_flags & SF_ABORT) ||
      *vroot_base == '\0') {
    /* NOTE: once stackable FS modules are supported, have this fall through
     * to the next module in the stack.
     */
    res = open(path, flags, PR_OPEN_MODE);
    return res;
  }

  if (vroot_lookup_path(NULL, vpath, sizeof(vpath)-1, path, 0, NULL) < 0)
    return -1;

  res = open(vpath, flags, PR_OPEN_MODE);
  return res;
}

#if PROFTPD_VERSION_NUMBER < 0x0001030603
static int vroot_creat(pr_fh_t *fh, const char *path, mode_t mode) {
  int res;
  char vpath[PR_TUNABLE_PATH_MAX + 1];

  if (session.curr_phase == LOG_CMD ||
      session.curr_phase == LOG_CMD_ERR ||
      (session.sf_flags & SF_ABORT) ||
      *vroot_base == '\0') {
    /* NOTE: once stackable FS modules are supported, have this fall through
     * to the next module in the stack.
     */
    res = creat(path, mode);
    return res;
  }

  if (vroot_lookup_path(NULL, vpath, sizeof(vpath)-1, path, 0, NULL) < 0)
    return -1;

  res = creat(vpath, mode);
  return res;
}
#endif /* ProFTPD 1.3.6rc2 or earlier */

static int vroot_link(pr_fs_t *fs, const char *path1, const char *path2) {
  int res;
  char vpath1[PR_TUNABLE_PATH_MAX + 1], vpath2[PR_TUNABLE_PATH_MAX + 1];

  if (session.curr_phase == LOG_CMD ||
      session.curr_phase == LOG_CMD_ERR ||
      (session.sf_flags & SF_ABORT) ||
      *vroot_base == '\0') {
    /* NOTE: once stackable FS modules are supported, have this fall through
     * to the next module in the stack.
     */
    res = link(path1, path2);
    return res;
  }

  if (vroot_lookup_path(NULL, vpath1, sizeof(vpath1)-1, path1, 0, NULL) < 0) {
    return -1;
  }

  if (vroot_lookup_path(NULL, vpath2, sizeof(vpath2)-1, path2, 0, NULL) < 0) {
    return -1;
  }

  res = link(vpath1, vpath2);
  return res;
}

static int vroot_symlink(pr_fs_t *fs, const char *path1, const char *path2) {
  int res;
  char vpath1[PR_TUNABLE_PATH_MAX + 1], vpath2[PR_TUNABLE_PATH_MAX + 1];

  if (session.curr_phase == LOG_CMD ||
      session.curr_phase == LOG_CMD_ERR ||
      (session.sf_flags & SF_ABORT) ||
      *vroot_base == '\0') {
    /* NOTE: once stackable FS modules are supported, have this fall through
     * to the next module in the stack.
     */
    res = symlink(path1, path2);
    return res;
  }

  if (vroot_lookup_path(NULL, vpath1, sizeof(vpath1)-1, path1, 0, NULL) < 0) {
    return -1;
  }

  if (vroot_lookup_path(NULL, vpath2, sizeof(vpath2)-1, path2, 0, NULL) < 0) {
    return -1;
  }

  res = symlink(vpath1, vpath2);
  return res;
}

static int vroot_readlink(pr_fs_t *fs, const char *readlink_path, char *buf,
    size_t max) {
  int res;
  char vpath[PR_TUNABLE_PATH_MAX + 1], *path = NULL, *alias_path = NULL;
  pool *tmp_pool = NULL;

  if (session.curr_phase == LOG_CMD ||
      session.curr_phase == LOG_CMD_ERR ||
      (session.sf_flags & SF_ABORT) ||
      *vroot_base == '\0') {
    /* NOTE: once stackable FS modules are supported, have this fall through
     * to the next module in the stack.
     */
    return readlink(readlink_path, buf, max);
  }

  /* In order to find any VRootAlias paths, we need to use the full path.
   * However, if we do NOT find any VRootAlias, then we do NOT want to use
   * the full path.
   */

  tmp_pool = make_sub_pool(session.pool);
  path = vroot_realpath(tmp_pool, readlink_path, VROOT_REALPATH_FL_ABS_PATH);

  if (vroot_lookup_path(tmp_pool, vpath, sizeof(vpath)-1, path, 0,
      &alias_path) < 0) {
    destroy_pool(tmp_pool);
    return -1;
  }

  if (alias_path == NULL) {
    if (vroot_lookup_path(NULL, vpath, sizeof(vpath)-1, readlink_path, 0,
        NULL) < 0) {
      destroy_pool(tmp_pool);
      return -1;
    }
  }

  res = readlink(vpath, buf, max);
  destroy_pool(tmp_pool);
  return res;
}

static int vroot_truncate(pr_fs_t *fs, const char *path, off_t length) {
  int res;
  char vpath[PR_TUNABLE_PATH_MAX + 1];

  if (session.curr_phase == LOG_CMD ||
      session.curr_phase == LOG_CMD_ERR ||
      (session.sf_flags & SF_ABORT) ||
      *vroot_base == '\0') {
    /* NOTE: once stackable FS modules are supported, have this fall through
     * to the next module in the stack.
     */
    res = truncate(path, length);
    return res;
  }

  if (vroot_lookup_path(NULL, vpath, sizeof(vpath)-1, path, 0, NULL) < 0)
    return -1;

  res = truncate(vpath, length);
  return res;
}

static int vroot_chmod(pr_fs_t *fs, const char *path, mode_t mode) {
  int res;
  char vpath[PR_TUNABLE_PATH_MAX + 1];

  if (session.curr_phase == LOG_CMD ||
      session.curr_phase == LOG_CMD_ERR ||
      (session.sf_flags & SF_ABORT) ||
      *vroot_base == '\0') {
    /* NOTE: once stackable FS modules are supported, have this fall through
     * to the next module in the stack.
     */
    res = chmod(path, mode);
    return res;
  }

  if (vroot_lookup_path(NULL, vpath, sizeof(vpath)-1, path, 0, NULL) < 0)
    return -1;

  res = chmod(vpath, mode);
  return res;
}

static int vroot_chown(pr_fs_t *fs, const char *path, uid_t uid, gid_t gid) {
  int res;
  char vpath[PR_TUNABLE_PATH_MAX + 1];

  if (session.curr_phase == LOG_CMD ||
      session.curr_phase == LOG_CMD_ERR ||
      (session.sf_flags & SF_ABORT) ||
      *vroot_base == '\0') {
    /* NOTE: once stackable FS modules are supported, have this fall through
     * to the next module in the stack.
     */
    res = chown(path, uid, gid);
    return res;
  }

  if (vroot_lookup_path(NULL, vpath, sizeof(vpath)-1, path, 0, NULL) < 0)
    return -1;

  res = chown(vpath, uid, gid);
  return res;
}

#if PROFTPD_VERSION_NUMBER >= 0x0001030407
static int vroot_lchown(pr_fs_t *fs, const char *path, uid_t uid, gid_t gid) {
  int res;
  char vpath[PR_TUNABLE_PATH_MAX + 1];

  if (session.curr_phase == LOG_CMD ||
      session.curr_phase == LOG_CMD_ERR ||
      (session.sf_flags & SF_ABORT) ||
      *vroot_base == '\0') {
    /* NOTE: once stackable FS modules are supported, have this fall through
     * to the next module in the stack.
     */
    res = lchown(path, uid, gid);
    return res;
  }

  if (vroot_lookup_path(NULL, vpath, sizeof(vpath)-1, path, 0, NULL) < 0)
    return -1;

  res = lchown(vpath, uid, gid);
  return res;
}
#endif /* ProFTPD 1.3.4c or later */

static int vroot_chroot(pr_fs_t *fs, const char *path) {
  char *chroot_path = "/", *tmp = NULL;
  config_rec *c;

  if (!path ||
      *path == '\0') {
    errno = EINVAL;
    return -1;
  }

  memset(vroot_base, '\0', sizeof(vroot_base));

  if (path[0] == '/' &&
      path[1] == '\0') {
    /* chrooting to '/', nothing needs to be done. */
    return 0;
  }

  c = find_config(main_server->conf, CONF_PARAM, "VRootServerRoot", FALSE);
  if (c) {
    int res;
    char *server_root, *ptr = NULL;

    server_root = c->argv[0];

    /* If the last character in the configured path is a slash, remove
     * it temporarily.
     */
    if (server_root[strlen(server_root)-1] == '/') {
      ptr = &(server_root[strlen(server_root)-1]);
      *ptr = '\0';
    }

    /* Now, make sure that the given path is below the configured
     * VRootServerRoot.  If so, then we perform a real chroot to the
     * VRootServerRoot directory, then use vroots from there.
     */ 

    res = strncmp(path, server_root, strlen(server_root));

    if (ptr != NULL) {
      *ptr = '/';
    }

    if (res == 0) {
      (void) pr_log_writefile(vroot_logfd, MOD_VROOT_VERSION,
        "chroot path '%s' within VRootServerRoot '%s', "
        "chrooting to VRootServerRoot", path, server_root);

      if (chroot(server_root) < 0) {
        (void) pr_log_writefile(vroot_logfd, MOD_VROOT_VERSION,
          "error chrooting to VRootServerRoot '%s': %s", server_root,
          strerror(errno));
        return -1;
      }

      pr_fs_clean_path(path + strlen(server_root), vroot_base,
        sizeof(vroot_base));
      chroot_path = server_root;

    } else {
      (void) pr_log_writefile(vroot_logfd, MOD_VROOT_VERSION,
        "chroot path '%s' is not within VRootServerRoot '%s', "
        "not chrooting to VRootServerRoot", path, server_root);
      pr_fs_clean_path(path, vroot_base, sizeof(vroot_base));
    }

  } else {
    pr_fs_clean_path(path, vroot_base, sizeof(vroot_base));
  }

  tmp = vroot_base;

  /* Advance to the end of the path. */
  while (*tmp != '\0') {
    tmp++;
  }

  for (;;) {
    tmp--;

    if (tmp == vroot_base ||
        *tmp != '/') {
      break;
    }

    *tmp = '\0';
  }

  vroot_baselen = strlen(vroot_base);
  if (vroot_baselen >= PR_TUNABLE_PATH_MAX) {
    errno = ENAMETOOLONG;
    return -1;
  }

  session.chroot_path = pstrdup(session.pool, chroot_path);
  return 0;
}

static int vroot_chdir(pr_fs_t *fs, const char *path) {
  int res;
  char vpath[PR_TUNABLE_PATH_MAX + 1], *vpathp = NULL, *alias_path = NULL;
  pool *tmp_pool = NULL;

  if (session.curr_phase == LOG_CMD ||
      session.curr_phase == LOG_CMD_ERR ||
      (session.sf_flags & SF_ABORT) ||
      *vroot_base == '\0') {
    /* NOTE: once stackable FS modules are supported, have this fall through
     * to the next module in the stack.
     */
    res = chdir(path);
    return res;
  }

  tmp_pool = make_sub_pool(session.pool);
  if (vroot_lookup_path(tmp_pool, vpath, sizeof(vpath)-1, path, 0,
      &alias_path) < 0) {
    destroy_pool(tmp_pool);
    return -1;
  }

  res = chdir(vpath);
  if (res < 0) {
    destroy_pool(tmp_pool);
    return -1;
  }

  if (alias_path != NULL) {
    vpathp = alias_path;

  } else {
    vpathp = vpath;
  }

  if (strncmp(vpathp, vroot_base, vroot_baselen) == 0) {
    pr_trace_msg(trace_channel, 19,
      "adjusting vpath '%s' to account for vroot base '%s' (%lu)", vpathp,
      vroot_base, (unsigned long) vroot_baselen);
    vpathp += vroot_baselen;
  }

  pr_trace_msg(trace_channel, 19,
    "setting current working directory to '%s'", vpathp);

  /* pr_fs_setcwd() makes a copy of the argument path, so we can safely
   * destroy our temporary pool.
   */
  pr_fs_setcwd(vpathp);

  destroy_pool(tmp_pool);
  return 0;
}

static int vroot_utimes(pr_fs_t *fs, const char *utimes_path,
    struct timeval *tvs) {
  int res;
  char vpath[PR_TUNABLE_PATH_MAX + 1], *path = NULL;
  pool *tmp_pool = NULL;

  if (session.curr_phase == LOG_CMD ||
      session.curr_phase == LOG_CMD_ERR ||
      (session.sf_flags & SF_ABORT) ||
      *vroot_base == '\0') {
    /* NOTE: once stackable FS modules are supported, have this fall through
     * to the next module in the stack.
     */
    res = utimes(utimes_path, tvs);
    return res;
  }

  tmp_pool = make_sub_pool(session.pool);
  path = vroot_realpath(tmp_pool, utimes_path, VROOT_REALPATH_FL_ABS_PATH);
  
  if (vroot_lookup_path(NULL, vpath, sizeof(vpath)-1, path, 0, NULL) < 0) {
    destroy_pool(tmp_pool);
    return -1;
  }

  res = utimes(vpath, tvs);
  destroy_pool(tmp_pool);
  return res;
}

static struct dirent *vroot_dent = NULL;
static size_t vroot_dentsz = 0;

/* On most systems, dirent.d_name is an array into which we can copy the
 * name we want.
 *
 * However, on other systems (e.g. Solaris 2), dirent.d_name is an array size
 * of 1.  This approach makes use of the fact that the d_name member is the
 * last member of the struct, meaning that the actual size is variable.
 *
 * We need to Do The Right Thing(tm) in either case.
 */
static size_t vroot_dent_namesz = 0;

static array_header *vroot_dir_aliases = NULL;
static int vroot_dir_idx = -1;

static int vroot_alias_dirscan(const void *key_data, size_t key_datasz,
    const void *value_data, size_t value_datasz, void *user_data) {
  const char *alias_path = NULL, *dir_path = NULL, *real_path = NULL;
  char *ptr = NULL;
  size_t dir_pathlen;

  alias_path = key_data;
  real_path = value_data;
  dir_path = user_data;

  ptr = strrchr(alias_path, '/');
  if (ptr == NULL) {
    /* This is not likely to happen, but if it does, simply move to the
     * next item in the table.
     */
    return 0;
  }

  /* If the dir path and the real path are the same, skip this alias.
   * Otherwise we end up with an extraneous entry in the directory listing.
   */
  if (strcmp(real_path, dir_path) == 0) {
    return 0;
  }

  dir_pathlen = strlen(dir_path);

  if (strncmp(dir_path, alias_path, dir_pathlen) == 0) {
    pr_trace_msg(trace_channel, 17,
      "adding VRootAlias '%s' to list of aliases contained in '%s'",
      alias_path, dir_path);
    *((char **) push_array(vroot_dir_aliases)) = pstrdup(vroot_dir_pool,
      ptr + 1);
  }

  return 0;
}

static int vroot_dirtab_keycmp_cb(const void *key1, size_t keysz1,
    const void *key2, size_t keysz2) {
  unsigned long k1, k2;

  memcpy(&k1, key1, sizeof(k1));
  memcpy(&k2, key2, sizeof(k2));

  return (k1 == k2 ? 0 : 1);
}

static unsigned int vroot_dirtab_hash_cb(const void *key, size_t keysz) {
  unsigned long h;

  memcpy(&h, key, sizeof(h));
  return h;
}

static void *vroot_opendir(pr_fs_t *fs, const char *orig_path) {
  int res;
  char vpath[PR_TUNABLE_PATH_MAX + 1], *path = NULL;
  void *dirh = NULL;
  struct stat st;
  size_t pathlen = 0;
  pool *tmp_pool = NULL;

  if (session.curr_phase == LOG_CMD ||
      session.curr_phase == LOG_CMD_ERR ||
      (session.sf_flags & SF_ABORT) ||
      *vroot_base == '\0') {
    /* NOTE: once stackable FS modules are supported, have this fall through
     * to the next module in the stack.
     */
    dirh = opendir(orig_path);
    return dirh;
  }

  tmp_pool = make_sub_pool(session.pool);

  /* If the given path ends in a slash, remove it.  The handling of
   * VRootAliases is sensitive to trailing slashes.
   */
  path = pstrdup(tmp_pool, orig_path);
  vroot_clean_path(path);

  /* If the given path ends in a slash, remove it.  The handling of
   * VRootAliases is sensitive to such things.
   */
  pathlen = strlen(path);
  if (pathlen > 1 &&
      path[pathlen-1] == '/') {
    path[pathlen-1] = '\0';
    pathlen--;
  }

  if (vroot_lookup_path(NULL, vpath, sizeof(vpath)-1, path, 0, NULL) < 0) {
    destroy_pool(tmp_pool);
    return NULL;
  }

  /* Check if the looked-up vpath is a symlink; we may need to resolve any
   * links ourselves, rather than assuming that the system opendir(3) can
   * handle it.
   */

  res = vroot_lstat(fs, vpath, &st);
  while (res == 0 &&
         S_ISLNK(st.st_mode)) {
    char data[PR_TUNABLE_PATH_MAX + 1];

    pr_signals_handle();

    memset(data, '\0', sizeof(data));
    res = vroot_readlink(fs, vpath, data, sizeof(data)-1);
    if (res < 0)
      break;

    data[res] = '\0';

    sstrncpy(vpath, data, sizeof(vpath));
    res = vroot_lstat(fs, vpath, &st);
  }

  dirh = opendir(vpath);
  if (dirh == NULL) {
    (void) pr_log_writefile(vroot_logfd, MOD_VROOT_VERSION,
      "error opening virtualized directory '%s' (from '%s'): %s", vpath, path,
      strerror(errno));
    destroy_pool(tmp_pool);
    return NULL;
  }

  if (vroot_aliastab != NULL) {
    unsigned long *cache_dirh = NULL;

    if (vroot_dirtab == NULL) {
      vroot_dir_pool = make_sub_pool(session.pool);
      pr_pool_tag(vroot_dir_pool, "VRoot Directory Pool");

      vroot_dirtab = pr_table_alloc(vroot_dir_pool, 0);

      /* Since this table will use DIR pointers as keys, we want to override
       * the default hashing and key comparison functions used.
       */
    
      pr_table_ctl(vroot_dirtab, PR_TABLE_CTL_SET_KEY_HASH,
        vroot_dirtab_hash_cb);
      pr_table_ctl(vroot_dirtab, PR_TABLE_CTL_SET_KEY_CMP,
        vroot_dirtab_keycmp_cb);
    }

    cache_dirh = palloc(vroot_dir_pool, sizeof(unsigned long));
    *cache_dirh = (unsigned long) dirh;

    if (pr_table_kadd(vroot_dirtab, cache_dirh, sizeof(unsigned long),
        pstrdup(vroot_dir_pool, vpath), strlen(vpath) + 1) < 0) {
      (void) pr_log_writefile(vroot_logfd, MOD_VROOT_VERSION,
        "error stashing path '%s' (key %p) in directory table: %s", vpath,
        dirh, strerror(errno));

    } else {
      vroot_dir_aliases = make_array(vroot_dir_pool, 0, sizeof(char *));

      res = pr_table_do(vroot_aliastab, vroot_alias_dirscan, vpath,
        PR_TABLE_DO_FL_ALL);
      if (res < 0) {
        (void) pr_log_writefile(vroot_logfd, MOD_VROOT_VERSION,
          "error doing dirscan on aliases table: %s", strerror(errno));

      } else {
        register unsigned int i;

        (void) pr_log_writefile(vroot_logfd, MOD_VROOT_VERSION,
          "found %d %s in directory '%s'", vroot_dir_aliases->nelts,
          vroot_dir_aliases->nelts != 1 ? "VRootAliases" : "VRootAlias",
          vpath);
        vroot_dir_idx = 0;

        for (i = 0; i < vroot_dir_aliases->nelts; i++) {
          char **elts = vroot_dir_aliases->elts;

          (void) pr_log_writefile(vroot_logfd, MOD_VROOT_VERSION,
            "'%s' aliases: [%u] %s", vpath, i, elts[i]);
        }
      }
    }
  }

  destroy_pool(tmp_pool);
  return dirh;
}

static struct dirent *vroot_readdir(pr_fs_t *fs, void *dirh) {
  struct dirent *dent = NULL;

next_dent:
  dent = readdir((DIR *) dirh);

  if (vroot_dir_aliases != NULL) {
    char **elts;

    elts = vroot_dir_aliases->elts;

    if (dent != NULL) {
      register unsigned int i;

      /* If this dent has the same name as an alias, the alias wins.
       * This is similar to a mounted filesystem, which hides any directories
       * underneath the mount point for the duration of the mount.
       */

      /* Yes, this is a linear scan; it assumes that the number of configured
       * aliases for a site will be relatively few.  Should this assumption
       * not be borne out by reality, then we should switch to using a
       * table, not an array_header, for storing the aliased paths.
       */

      for (i = 0; i < vroot_dir_aliases->nelts; i++) {
        if (strcmp(dent->d_name, elts[i]) == 0) {
          (void) pr_log_writefile(vroot_logfd, MOD_VROOT_VERSION,
            "skipping directory entry '%s', as it is aliased", dent->d_name);
          goto next_dent;
        }
      }

    } else {
      if (vroot_dir_idx < 0 ||
          vroot_dir_idx >= vroot_dir_aliases->nelts) {
        return NULL;
      }

      memset(vroot_dent, 0, vroot_dentsz);

      if (vroot_dent_namesz == 0) {
        sstrncpy(vroot_dent->d_name, elts[vroot_dir_idx++],
          sizeof(vroot_dent->d_name));

      } else {
        sstrncpy(vroot_dent->d_name, elts[vroot_dir_idx++],
          vroot_dent_namesz);
      }

      return vroot_dent;
    }
  }

  return dent;
}

static int vroot_closedir(pr_fs_t *fs, void *dirh) {
  int res;

  res = closedir((DIR *) dirh);

  if (vroot_dirtab != NULL) {
    unsigned long lookup_dirh;
    int count;

    lookup_dirh = (unsigned long) dirh;
    (void) pr_table_kremove(vroot_dirtab, &lookup_dirh, sizeof(unsigned long),
      NULL);

    /* If the dirtab table is empty, destroy the table. */
    count = pr_table_count(vroot_dirtab);

    if (count == 0) {
      pr_table_empty(vroot_dirtab);
      destroy_pool(vroot_dir_pool);
      vroot_dir_pool = NULL;
      vroot_dirtab = NULL;
      vroot_dir_aliases = NULL;
      vroot_dir_idx = -1;
    }
  }

  return res;
}

static int vroot_mkdir(pr_fs_t *fs, const char *path, mode_t mode) {
  int res;
  char vpath[PR_TUNABLE_PATH_MAX + 1];

  if (session.curr_phase == LOG_CMD ||
      session.curr_phase == LOG_CMD_ERR ||
      (session.sf_flags & SF_ABORT) ||
      *vroot_base == '\0') {
    /* NOTE: once stackable FS modules are supported, have this fall through
     * to the next module in the stack.
     */
    res = mkdir(path, mode);
    return res;
  }

  if (vroot_lookup_path(NULL, vpath, sizeof(vpath)-1, path, 0, NULL) < 0)
    return -1;

  res = mkdir(vpath, mode);
  return res;
}

static int vroot_rmdir(pr_fs_t *fs, const char *path) {
  int res;
  char vpath[PR_TUNABLE_PATH_MAX + 1];

  if (session.curr_phase == LOG_CMD ||
      session.curr_phase == LOG_CMD_ERR ||
      (session.sf_flags & SF_ABORT) ||
      *vroot_base == '\0') {
    /* NOTE: once stackable FS modules are supported, have this fall through
     * to the next module in the stack.
     */
    res = rmdir(path);
    return res;
  }

  /* Do not allow deleting of aliased files/directories; the aliases may only
   * exist for this user/group.
   */
  if (vroot_lookup_path(NULL, vpath, sizeof(vpath)-1, path,
      VROOT_LOOKUP_FL_NO_ALIASES, NULL) < 0) {
    return -1;
  }

  if (vroot_is_alias(vpath) == 0) {
    (void) pr_log_writefile(vroot_logfd, MOD_VROOT_VERSION,
      "denying delete of '%s' because it is a VRootAlias", vpath);
    errno = EACCES;
    return -1;
  }

  if (vroot_lookup_path(NULL, vpath, sizeof(vpath)-1, path, 0, NULL) < 0)
    return -1;

  res = rmdir(vpath);
  return res;
}

/* Configuration handlers
 */

/* usage: VRootAlias src-path dst-path */
MODRET set_vrootalias(cmd_rec *cmd) {
  config_rec *c;

  CHECK_ARGS(cmd, 2);
  CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);

  if (pr_fs_valid_path(cmd->argv[1]) < 0) {
    CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "source path '", cmd->argv[1],
      "' is not an absolute path", NULL));
  }

  c = add_config_param_str(cmd->argv[0], 2, cmd->argv[1], cmd->argv[2]);

  /* Set this flag in order to allow mod_ifsession to work properly with
   * multiple VRootAlias directives.
   */
  c->flags |= CF_MERGEDOWN_MULTI;

  return PR_HANDLED(cmd);
}

/* usage: VRootEngine on|off */
MODRET set_vrootengine(cmd_rec *cmd) {
  int bool = -1;
  config_rec *c = NULL;

  CHECK_ARGS(cmd, 1);
  CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);

  bool = get_boolean(cmd, 1);
  if (bool == -1)
    CONF_ERROR(cmd, "expected Boolean parameter");

  c = add_config_param(cmd->argv[0], 1, NULL);
  c->argv[0] = pcalloc(c->pool, sizeof(unsigned char));
  *((unsigned char *) c->argv[0]) = bool;

  return PR_HANDLED(cmd);
}

/* usage: VRootLog path|"none" */
MODRET set_vrootlog(cmd_rec *cmd) {
  CHECK_ARGS(cmd, 1);
  CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);

  if (pr_fs_valid_path(cmd->argv[1]) < 0)
    CONF_ERROR(cmd, "must be an absolute path");

  (void) add_config_param_str(cmd->argv[0], 1, cmd->argv[1]);
  return PR_HANDLED(cmd);
}

/* usage: VRootOptions opt1 opt2 ... optN */
MODRET set_vrootoptions(cmd_rec *cmd) {
  config_rec *c = NULL;
  register unsigned int i;
  unsigned int opts = 0U;

  if (cmd->argc-1 == 0)
    CONF_ERROR(cmd, "wrong number of parameters");

  CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);

  c = add_config_param(cmd->argv[0], 1, NULL);
  for (i = 1; i < cmd->argc; i++) {
    if (strcmp(cmd->argv[i], "allowSymlinks") == 0) {
      opts |= VROOT_OPT_ALLOW_SYMLINKS;

    } else {
      CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, ": unknown VRootOption: '",
        cmd->argv[i], "'", NULL));
    }
  }

  c->argv[0] = pcalloc(c->pool, sizeof(unsigned int));
  *((unsigned int *) c->argv[0]) = opts;

  return PR_HANDLED(cmd);
}

/* usage: VRootServerRoot path */
MODRET set_vrootserverroot(cmd_rec *cmd) {
  struct stat st;
  config_rec *c;
  char *path;
  size_t pathlen;

  CHECK_ARGS(cmd, 1);
  CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);

  path = cmd->argv[1];

  if (pr_fs_valid_path(path) < 0)
    CONF_ERROR(cmd, "must be an absolute path");

  if (stat(path, &st) < 0) {
    CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "error checking '", path, "': ",
      strerror(errno), NULL));
  }

  if (!S_ISDIR(st.st_mode)) {
    CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", path, "' is not a directory",
      NULL));
  }

  c = add_config_param(cmd->argv[0], 1, NULL);

  /* Make sure the configured path has a trailing path separater ('/').
   * This is important.
   */
 
  pathlen = strlen(path);
  if (path[pathlen - 1] != '/') {
    c->argv[0] = pstrcat(c->pool, path, "/", NULL);

  } else {
    c->argv[0] = pstrdup(c->pool, path);
  }

  return PR_HANDLED(cmd);
}

/* Command handlers
 */

MODRET vroot_log_retr(cmd_rec *cmd) {
  const char *key, *path;

  if (vroot_engine == FALSE ||
      session.chroot_path == NULL) {
    return PR_DECLINED(cmd);
  }

  key = "mod_xfer.retr-path";

  path = pr_table_get(cmd->notes, key, NULL);
  if (path != NULL) {
    char *real_path;

    if (*path == '/') {
      real_path = pdircat(cmd->pool, vroot_base, path, NULL);
      vroot_clean_path(real_path);

    } else {
      real_path = vroot_realpath(cmd->pool, path, VROOT_REALPATH_FL_ABS_PATH);
    }

    pr_table_set(cmd->notes, key, real_path, 0);
  }

  return PR_DECLINED(cmd);
}

MODRET vroot_log_stor(cmd_rec *cmd) {
  const char *key, *path;

  if (vroot_engine == FALSE ||
      session.chroot_path == NULL) {
    return PR_DECLINED(cmd);
  }

  key = "mod_xfer.store-path";

  path = pr_table_get(cmd->notes, key, NULL);
  if (path != NULL) {
    char *real_path;

    if (*path == '/') {
      real_path = pdircat(cmd->pool, vroot_base, path, NULL);
      vroot_clean_path(real_path);

    } else {
      real_path = vroot_realpath(cmd->pool, path, VROOT_REALPATH_FL_ABS_PATH);
    }

    pr_table_set(cmd->notes, key, real_path, 0);
  }

  return PR_DECLINED(cmd);
}

MODRET vroot_pre_mkd(cmd_rec *cmd) {
  if (vroot_engine == FALSE ||
      session.chroot_path == NULL) {
    return PR_DECLINED(cmd);
  }

#if PROFTPD_VERSION_NUMBER >= 0x0001030407
  vroot_use_mkdtemp = pr_fsio_set_use_mkdtemp(FALSE);
#endif /* ProFTPD 1.3.4c or later */

  return PR_DECLINED(cmd);
}

MODRET vroot_post_mkd(cmd_rec *cmd) {
  if (vroot_engine == FALSE ||
      session.chroot_path == NULL) {
    return PR_DECLINED(cmd);
  }

#if PROFTPD_VERSION_NUMBER >= 0x0001030407
  pr_fsio_set_use_mkdtemp(vroot_use_mkdtemp);
#endif /* ProFTPD 1.3.4c or later */

  return PR_DECLINED(cmd);
}

MODRET vroot_pre_pass(cmd_rec *cmd) {
  pr_fs_t *fs = NULL;
  unsigned char *use_vroot = NULL;

  use_vroot = get_param_ptr(main_server->conf, "VRootEngine", FALSE); 

  if (!use_vroot ||
      *use_vroot == FALSE) {
    vroot_engine = FALSE;
    return PR_DECLINED(cmd);
  }

  /* First, make sure that we have not already registered our FS object. */
  fs = pr_unmount_fs("/", "vroot");
  if (fs) {
    destroy_pool(fs->fs_pool);
  }

  fs = pr_register_fs(main_server->pool, "vroot", "/");
  if (fs == NULL) {
    pr_log_debug(DEBUG3, MOD_VROOT_VERSION ": error registering fs: %s",
      strerror(errno));
    return PR_DECLINED(cmd);
  }

  pr_log_debug(DEBUG5, MOD_VROOT_VERSION ": vroot registered");

  /* Add the module's custom FS callbacks here. This module does not
   * provide callbacks for the following (as they are unnecessary):
   * close(), read(), write(), and lseek().
   */
  fs->stat = vroot_stat;
  fs->lstat = vroot_lstat;
  fs->rename = vroot_rename;
  fs->unlink = vroot_unlink;
  fs->open = vroot_open;
#if PROFTPD_VERSION_NUMBER < 0x0001030603
  fs->creat = vroot_creat;
#endif /* ProFTPD 1.3.6rc2 or earlier */
  fs->link = vroot_link;
  fs->readlink = vroot_readlink;
  fs->symlink = vroot_symlink;
  fs->truncate = vroot_truncate;
  fs->chmod = vroot_chmod;
  fs->chown = vroot_chown;
#if PROFTPD_VERSION_NUMBER >= 0x0001030407
  fs->lchown = vroot_lchown;
#endif /* ProFTPD 1.3.4c or later */
  fs->chdir = vroot_chdir;
  fs->chroot = vroot_chroot;
  fs->utimes = vroot_utimes;
  fs->opendir = vroot_opendir;
  fs->readdir = vroot_readdir;
  fs->closedir = vroot_closedir;
  fs->mkdir = vroot_mkdir;
  fs->rmdir = vroot_rmdir;

  vroot_engine = TRUE;
  return PR_DECLINED(cmd);
}

MODRET vroot_post_pass(cmd_rec *cmd) {
  if (vroot_engine) {

    /* If not chrooted, unregister vroot. */
    if (!session.chroot_path) {
      if (pr_unregister_fs("/") < 0) {
        pr_log_debug(DEBUG2, MOD_VROOT_VERSION
          ": error unregistering vroot: %s", strerror(errno));

      } else {
        pr_log_debug(DEBUG5, MOD_VROOT_VERSION ": vroot unregistered");
        pr_fs_setcwd(pr_fs_getvwd());
        pr_fs_clear_cache();
      }

    } else {
      config_rec *c;

      /* Otherwise, lookup and process any VRootOptions. */
      c = find_config(main_server->conf, CONF_PARAM, "VRootOptions", FALSE);
      if (c) {
        vroot_opts = *((unsigned int *) c->argv[0]);
      }

      /* XXX This needs to be in the PRE_CMD PASS handler, as when
       * VRootServer is used, so that a real chroot(2) occurs.
       */
      handle_vroot_alias();
    }
  }

  return PR_DECLINED(cmd);
}

MODRET vroot_post_pass_err(cmd_rec *cmd) {
  if (vroot_engine) {

    /* If not chrooted, unregister vroot. */
    if (session.chroot_path == NULL) {
      if (pr_unregister_fs("/") < 0) {
        pr_log_debug(DEBUG2, MOD_VROOT_VERSION
          ": error unregistering vroot: %s", strerror(errno));

      } else {
        pr_log_debug(DEBUG5, MOD_VROOT_VERSION ": vroot unregistered");
      }
    }

    if (vroot_aliastab) {
      pr_table_empty(vroot_aliastab);
      destroy_pool(vroot_alias_pool);
      vroot_alias_pool = NULL;
      vroot_aliastab = NULL;
    }
  }

  return PR_DECLINED(cmd);
}

/* Initialization routines
 */

static int vroot_sess_init(void) {
  config_rec *c;
  struct dirent dent;

  c = find_config(main_server->conf, CONF_PARAM, "VRootLog", FALSE);
  if (c) {
    vroot_log = c->argv[0];
  }

  if (vroot_log &&
      strcasecmp(vroot_log, "none") != 0) {
    int res;

    PRIVS_ROOT
    res = pr_log_openfile(vroot_log, &vroot_logfd, 0660);
    PRIVS_RELINQUISH

    switch (res) {
      case 0:
        break;

      case -1:
        pr_log_debug(DEBUG1, MOD_VROOT_VERSION
          ": unable to open VRootLog '%s': %s", vroot_log, strerror(errno));
        break;

      case PR_LOG_SYMLINK:
        pr_log_debug(DEBUG1, MOD_VROOT_VERSION
          ": unable to open VRootLog '%s': %s", vroot_log, "is a symlink");
        break;

      case PR_LOG_WRITABLE_DIR:
        pr_log_debug(DEBUG1, MOD_VROOT_VERSION
          ": unable to open VRootLog '%s': %s", vroot_log,
          "parent directory is world-writable");
        break;
    }
  }

  /* Allocate the memory for the static struct dirent that we use, including
   * determining the necessary sizes.
   */
  vroot_dentsz = sizeof(dent);
  if (sizeof(dent.d_name) == 1) {
    /* Allocate extra space for the dent path name. */
    vroot_dent_namesz = PR_TUNABLE_PATH_MAX;
  }

  vroot_dentsz += vroot_dent_namesz;
  vroot_dent = palloc(session.pool, vroot_dentsz);

  return 0;
}

/* Module API tables
 */

static conftable vroot_conftab[] = {
  { "VRootAlias",	set_vrootalias,		NULL },
  { "VRootEngine",	set_vrootengine,	NULL },
  { "VRootLog",		set_vrootlog,		NULL },
  { "VRootOptions",	set_vrootoptions,	NULL },
  { "VRootServerRoot",	set_vrootserverroot,	NULL },
  { NULL }
};

static cmdtable vroot_cmdtab[] = {
  { PRE_CMD,		C_PASS,	G_NONE,	vroot_pre_pass, FALSE, FALSE },
  { POST_CMD,		C_PASS,	G_NONE,	vroot_post_pass, FALSE, FALSE },
  { POST_CMD_ERR,	C_PASS,	G_NONE,	vroot_post_pass_err, FALSE, FALSE },

  { PRE_CMD,		C_MKD,	G_NONE,	vroot_pre_mkd, FALSE, FALSE },
  { POST_CMD,		C_MKD,	G_NONE,	vroot_post_mkd, FALSE, FALSE },
  { POST_CMD_ERR,	C_MKD,	G_NONE,	vroot_post_mkd, FALSE, FALSE },
  { PRE_CMD,		C_XMKD,	G_NONE,	vroot_pre_mkd, FALSE, FALSE },
  { POST_CMD,		C_XMKD,	G_NONE,	vroot_post_mkd, FALSE, FALSE },
  { POST_CMD_ERR,	C_XMKD,	G_NONE,	vroot_post_mkd, FALSE, FALSE },

  /* These command handlers are for manipulating cmd->notes, to get
   * paths properly logged.
   *
   * Ideally these would be LOG_CMD/LOG_CMD_ERR phase handlers.  HOWEVER,
   * we need to transform things before the cmd is dispatched to mod_log,
   * and mod_log uses a C_ANY handler for logging.  And when dispatching,
   * C_ANY handlers are run before named handlers.  This means that using
   * LOG_CMD/LOG_CMD_ERR handlers would be run AFTER mod_log's handler,
   * even though we appear BEFORE mod_log in the module load order.
   *
   * Thus to do the transformation, we actually use POST_CMD/POST_CMD_ERR
   * phase handlers here.
   */
  { POST_CMD,		C_APPE,	G_NONE, vroot_log_stor, FALSE, FALSE },
  { POST_CMD_ERR,	C_APPE,	G_NONE, vroot_log_stor, FALSE, FALSE },
  { POST_CMD,		C_RETR,	G_NONE, vroot_log_retr, FALSE, FALSE },
  { POST_CMD_ERR,	C_RETR,	G_NONE, vroot_log_retr, FALSE, FALSE },
  { POST_CMD,		C_STOR,	G_NONE, vroot_log_stor, FALSE, FALSE },
  { POST_CMD_ERR,	C_STOR,	G_NONE, vroot_log_stor, FALSE, FALSE },

  { 0, NULL }
};

module vroot_module = {
  NULL, NULL,

  /* Module API version 2.0 */
  0x20,

  /* Module name */
  "vroot",

  /* Module configuration handler table */
  vroot_conftab,

  /* Module command handler table */
  vroot_cmdtab,

  /* Module authentication handler table */
  NULL,

  /* Module initialization function */
  NULL,

  /* Session initialization function */
  vroot_sess_init,

  /* Module version */
  MOD_VROOT_VERSION
};