File: mod_wrap2.c

package info (click to toggle)
proftpd-dfsg 1.3.4a-5%2Bdeb7u3
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 27,820 kB
  • sloc: perl: 154,169; ansic: 128,582; sh: 13,564; php: 11,586; makefile: 2,156
file content (2044 lines) | stat: -rw-r--r-- 52,028 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
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
/*
 * ProFTPD: mod_wrap2 -- tcpwrappers-like access control
 *
 * Copyright (c) 2000-2011 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., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA.
 *
 * As a special exemption, TJ Saunders gives permission to link this program
 * with OpenSSL, and distribute the resulting executable, without including
 * the source code for OpenSSL in the source distribution.
 */

#include "mod_wrap2.h"

#ifdef WRAP2_USE_NIS
#include <rpc/rpc.h>
#include <rpcsvc/ypclnt.h>
#endif /* WRAP2_USE_NIS */

typedef struct regtab_obj {
  struct regtab_obj *prev, *next;

  /* Table source type name */
  const char *regtab_name;

  /* Initialization function for this type of table source */
  wrap2_table_t *(*regtab_open)(pool *, char *);

} wrap2_regtab_t;

module wrap2_module;
unsigned long wrap2_opts = 0UL;

/* Wrap tables for the current session */
static char *wrap2_allow_table = NULL;
static char *wrap2_deny_table = NULL;

/* Memory pool for this module */
static pool *wrap2_pool = NULL;

/* List of registered quotatab sources */
static wrap2_regtab_t *wrap2_regtab_list = NULL;

/* Logging data */
static int wrap2_logfd = -1;
static char *wrap2_logname = NULL;

static int wrap2_engine = FALSE;
static char *wrap2_service_name = WRAP2_DEFAULT_SERVICE_NAME;
static char *wrap2_client_name = NULL;
static config_rec *wrap2_ctxt = NULL;

/* Access check variables */

#define WRAP2_UNKNOWN	"unknown"
#define WRAP2_PARANOID	"paranoid"

#define WRAP2_IS_KNOWN_HOSTNAME(s) \
  (strcasecmp((s), WRAP2_UNKNOWN) != 0 && strcasecmp((s), WRAP2_PARANOID))

#define WRAP2_IS_NOT_INADDR(s) \
  (s[strspn(s,"01234567890./")] != 0)

#define WRAP2_GET_DAEMON(r) \
  ((r)->daemon)

/* Data structures */

typedef struct host_info {
  char name[WRAP2_BUFFER_SIZE];
  char addr[WRAP2_BUFFER_SIZE];
  struct sockaddr_in *sin;            /* socket address or 0 */
  struct t_unitdata *unit;            /* TLI transport address or 0 */
  struct conn_info *connection;       /* for shared information */

} wrap2_host_t;

typedef struct conn_info {
  int sock_fd;                         /* socket handle */
  char user[WRAP2_BUFFER_SIZE];        /* access via eval_user(request) */
  char daemon[WRAP2_BUFFER_SIZE];      /* access via eval_daemon(request) */
  struct host_info client[1];         /* client endpoint info */
  struct host_info server[1];         /* server endpoint info */
  void  (*sink) (int);                /* datagram sink function or 0 */
  void  (*hostname) (struct host_info *); /* address to printable hostname */
  void  (*hostaddr) (struct host_info *); /* address to printable address */
  void  (*cleanup) (struct conn_info *);   /* cleanup function or 0 */
  struct netconfig *config;           /* netdir handle */

} wrap2_conn_t;

#define WRAP2_CONN_SOCK_FD	1	/* socket descriptor */
#define WRAP2_CONN_DAEMON	2	/* server process (argv[0]) */

#ifndef INADDR_NONE
#define INADDR_NONE 0xffffffff
#endif

/* Logging routines */

static int wrap2_closelog(void) {
  if (wrap2_logfd != -1) {
    close(wrap2_logfd);
    wrap2_logfd = -1;
    wrap2_logname = NULL;
  }

  return 0;
}

int wrap2_log(const char *fmt, ...) {
  va_list msg;
  int res;

  if (!wrap2_logname)
    return 0;

  va_start(msg, fmt);
  res = pr_log_vwritefile(wrap2_logfd, MOD_WRAP2_VERSION, fmt, msg);
  va_end(msg);

  return res;
}

static int wrap2_openlog(void) {
  int res = 0;

  /* Sanity check */
  wrap2_logname = get_param_ptr(main_server->conf, "WrapLog", FALSE);
  if (wrap2_logname == NULL)
    return 0;

  /* Check for "none" */
  if (strcasecmp(wrap2_logname, "none") == 0) {
    wrap2_logname = NULL;
    return 0;
  }

  pr_signals_block();
  PRIVS_ROOT
  res = pr_log_openfile(wrap2_logname, &wrap2_logfd, 0640);
  PRIVS_RELINQUISH
  pr_signals_unblock();

  return res;
}

/* Table routines */

static int wrap2_close_table(wrap2_table_t *tab) {
  return tab->tab_close(tab);
}

static wrap2_table_t *wrap2_open_table(char *name) {
  char *info = NULL, *ptr = NULL;
  unsigned char have_type = FALSE;
  register wrap2_regtab_t *regtab = NULL;
  wrap2_table_t *tab = NULL;

  info = ptr = strchr(name, ':');
  *info++ = '\0';

  /* Look up the table source open routine by name, and invoke it */
  for (regtab = wrap2_regtab_list; regtab; regtab = regtab->next) {
    if (strcmp(regtab->regtab_name, name) == 0) {
      tab = regtab->regtab_open(wrap2_pool, info);
      if (tab == NULL) {
        *ptr = ':';
        return NULL;
      }

      have_type = TRUE;
      *ptr = ':';
      break;
    }
  }

  if (!have_type) {
    wrap2_log("unsupported table source: '%s'", name);
    errno = EINVAL;
    return NULL;
  }

  return tab;
}

/* Information structure routines */

static wrap2_conn_t *wrap2_conn_update(wrap2_conn_t *conn, va_list ap) {
  int key = 0;
  char *val = NULL;

  while ((key = va_arg(ap, int)) > 0) {
    switch (key) {

      default:
        wrap2_log("invalid key: %d", key);
        return conn;

      case WRAP2_CONN_SOCK_FD:
        conn->sock_fd = va_arg(ap, int);
        continue;

#if 0
      case WRAP2_CONN_CLIENT_SIN:
        conn->client->sin = va_arg(ap, struct sockaddr_in *);
        continue;

      case WRAP2_CONN_SERVER_SIN:
        conn->server->sin = va_arg(ap, struct sockaddr_in *);
        continue;
#endif

      case WRAP2_CONN_DAEMON:
        val = conn->daemon;
        break;

#if 0
      case WRAP2_CONN_USER:
        val = conn->user;
        break;

      case WRAP2_CONN_CLIENT_NAME:
        val = conn->client->name;
        break;

      case WRAP2_CONN_CLIENT_ADDR:
        val = conn->client->addr;
        break;

      case WRAP2_CONN_SERVER_NAME:
        val = conn->server->name;
        break;

      case WRAP2_CONN_SERVER_ADDR:
        val = conn->server->addr;
        break;
#endif
    }

    /* Copy in the string */
    sstrncpy(val, va_arg(ap, char *), WRAP2_BUFFER_SIZE);
  }

  return conn;
}

static wrap2_conn_t *wrap2_conn_set(wrap2_conn_t *conn, ...) {
  static wrap2_conn_t default_conn;
  wrap2_conn_t *c = NULL;
  va_list ap;

  /* Initialize the data members.  We do not assign default callbacks,
   * to avoid pulling in the whole socket module when it is not really
   * needed.
   */
  va_start(ap, conn);

  *conn = default_conn;

  conn->sock_fd = -1;
  sstrncpy(conn->daemon, WRAP2_UNKNOWN, sizeof(conn->daemon));

  conn->client->connection = conn;
  conn->server->connection = conn;

  c = wrap2_conn_update(conn, ap);
  va_end(ap);

  return c;
}

static char *wrap2_get_user(wrap2_conn_t *conn) {

  if (*conn->user == '\0') {
    char *rfc1413_ident;

    /* RFC1413 lookups may have already been done by the mod_ident module.
     * If so, use the ident name stashed; otherwise, use the user name issued
     * by the client.
     */

    rfc1413_ident = pr_table_get(session.notes, "mod_ident.rfc1413-ident",
      NULL);
    if (rfc1413_ident) {
      sstrncpy(conn->user, rfc1413_ident, sizeof(conn->user));

    } else {
      char *user;

      user = pr_table_get(session.notes, "mod_auth.orig-user", NULL);
      if (user) {
        sstrncpy(conn->user, user, sizeof(conn->user));
      }
    }
  }

  return conn->user;
}

static char *wrap2_get_hostaddr(wrap2_host_t *host) {
  if (*host->addr == '\0') {
    sstrncpy(host->addr, pr_netaddr_get_ipstr(session.c->remote_addr),
      sizeof(host->addr));
  }

  return host->addr;
}

static char *wrap2_get_hostname(wrap2_host_t *host) {

  if (*host->name == '\0') {
    int reverse_dns;
    size_t namelen;

    /* Manually tweak the UseReverseDNS setting, and any caches, so that
     * we really do use the DNS name here if possible.
     */
    pr_netaddr_clear_cache();

    reverse_dns = pr_netaddr_set_reverse_dns(TRUE);
    session.c->remote_addr->na_have_dnsstr = FALSE;
    sstrncpy(host->name, pr_netaddr_get_dnsstr(session.c->remote_addr),
      sizeof(host->name));

    /* If the retrieved hostname ends in a trailing period, trim it off. */
    namelen = strlen(host->name); 
    if (host->name[namelen-1] == '.') {
      host->name[namelen-1] = '\0';
      namelen--;
    }

    pr_netaddr_set_reverse_dns(reverse_dns);
    session.c->remote_addr->na_have_dnsstr = TRUE;
  }

  return host->name;
}

static char *wrap2_get_hostinfo(wrap2_host_t *host) {
  char *hostname = wrap2_get_hostname(host);

  if (WRAP2_IS_KNOWN_HOSTNAME(hostname))
    return hostname;

  return wrap2_get_hostaddr(host);
}

static char *wrap2_get_client(wrap2_conn_t *conn) {
  static char both[WRAP2_BUFFER_SIZE] = {'\0'};
  char *hostinfo = wrap2_get_hostinfo(conn->client);

  if (strcasecmp(wrap2_get_user(conn), WRAP2_UNKNOWN) != 0) {
    snprintf(both, sizeof(both), "%s@%s", conn->user, hostinfo);
    both[sizeof(both)-1] = '\0';
    return both;
  }

  return hostinfo;
}

/* Access checking routines */

char *wrap2_strsplit(char *str, int delim) {
  char *tmp = NULL;

  tmp = strchr(str, delim);
  if (tmp != NULL)
    *tmp++ = '\0';

  return tmp;
}

static char *wrap2_skip_whitespace(char *str) {
  register unsigned int i;
  char *tmp;

  /* Skip any leading whitespace. */
  tmp = str;
  for (i = 0; str[i]; i++) {
    if (isspace((int) str[i])) {
      tmp = &str[i+1];
      continue;
    }

    break;
  }

  return tmp;
}

static unsigned char wrap2_match_string(const char *tok, const char *str) {
  size_t len = 0;

  if (tok[0] == '.') {

    /* Suffix */
    len = strlen(str) - strlen(tok);
    return (len > 0 && (strcasecmp(tok, str + len) == 0));

  } else if (strcasecmp(tok, "ALL") == 0) {
    /* ALL: match any */
    return TRUE;

  } else if (strcasecmp(tok, "KNOWN") == 0) {

    /* Not unknown */
    return (strcasecmp(str, WRAP2_UNKNOWN) != 0);

  } else if (tok[(len = strlen(tok)) - 1] == '.') {

    /* Prefix */
    return (strncasecmp(tok, str, len) == 0);
  }

  /* Exact match */
  return (strcasecmp(tok, str) == 0);
}

static unsigned long wrap2_addr_a2n(const char *str) {
  unsigned char within_run = FALSE;
  unsigned int nruns = 0;
  const char *cp = str;

  /* Count the number of runs of non-dot characters. */

  while (*cp) {
    if (*cp == '.') {
      within_run = FALSE;

    } else if (within_run == FALSE) {
      within_run = TRUE;
      nruns++;
    }
    cp++;
  }

  return (nruns == 4 ? inet_addr(str) : INADDR_NONE);
}

static unsigned char wrap2_match_netmask(const char *net_tok,
    const char *mask_tok, const char *str) {
  unsigned long net = 0UL;
  unsigned long mask = 0UL;
  unsigned long addr = 0UL;

  /* Disallow forms other than dotted quad: the treatment that inet_addr()
   * gives to forms with less than four components is inconsistent with the
   * access control language. John P. Rouillard <rouilj@cs.umb.edu>.
   */

  addr = wrap2_addr_a2n(str);
  if (addr == INADDR_NONE) {
    return FALSE;
  }

  net = wrap2_addr_a2n(net_tok);
  mask = wrap2_addr_a2n(mask_tok);
  if (net == INADDR_NONE ||
      mask == INADDR_NONE) {
    wrap2_log("warning: bad net/mask expression: '%s/%s'", net_tok, mask_tok);
    return FALSE;
  }

  return ((addr & mask) == net);
}

static unsigned char wrap2_match_host(char *tok, wrap2_host_t *host) {
  char *mask = NULL;
  size_t len;

  tok = wrap2_skip_whitespace(tok);

  /* This code looks a little hairy because we want to avoid unnecessary
   * hostname lookups.
   *
   * The KNOWN pattern requires that both address AND name be known; some
   * patterns are specific to host names or to host addresses; all other
   * patterns are satisfied when either the address OR the name match.
   */

  if (tok[0] == '@') {
#ifdef WRAP2_USE_NIS
    /* netgroup: look it up. */
    static char *mydomain = NULL;

    if (mydomain == NULL)
      yp_get_default_domain(&mydomain);

    return (innetgr(tok + 1, wrap2_get_hostname(host), NULL, mydomain));
#else
    wrap2_log("warning: '%s': NIS support is not enabled", tok);
    return FALSE;
#endif

  } else if (strcasecmp(tok, "ALL") == 0) {
    /* Matches everything */
    return TRUE;

  } else if (strcasecmp(tok, "KNOWN") == 0) {

    /* Check address and name. */
    char *name = wrap2_get_hostname(host);
    return ((strcasecmp(wrap2_get_hostaddr(host), WRAP2_UNKNOWN) != 0) &&
      WRAP2_IS_KNOWN_HOSTNAME(name));

  } else if (strcasecmp(tok, "LOCAL") == 0) {

    /* Local: no dots in name. */
    char *name = wrap2_get_hostname(host);
    return (strchr(name, '.') == NULL && WRAP2_IS_KNOWN_HOSTNAME(name));

  } else if (tok[(len = strlen(tok)) - 1] == '.') {
    const char *ip_str;
 
    /* Prefix */

    ip_str = wrap2_get_hostaddr(host);
    return (strncasecmp(tok, ip_str, len) == 0);

  } else if (tok[0] == '.') {
    register unsigned int i;
    char *primary_name;
    array_header *dns_names;

    /* Suffix */
    primary_name = wrap2_get_hostname(host);
    len = strlen(primary_name) - strlen(tok);

    wrap2_log("comparing client hostname '%s' (part %s) against DNS "
      "pattern '%s'", primary_name, primary_name+len, tok);

    if (len > 0 &&
        strcasecmp(tok, primary_name + len) == 0) {
      return TRUE;
    }

    if (!(wrap2_opts & WRAP_OPT_CHECK_ALL_NAMES)) {
      return FALSE;
    }

    dns_names = pr_netaddr_get_dnsstr_list(session.pool,
      session.c->remote_addr);
    if (dns_names != NULL &&
        dns_names->nelts > 0) {
      char **names;

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

        name = names[i];
        if (name != NULL) {
          len = strlen(name) - strlen(tok);

          wrap2_log("comparing client hostname '%s' (part %s) against DNS "
            "pattern '%s'", name, name+len, tok);

          if (len > 0 &&
              strcasecmp(tok, name + len) == 0) {
            return TRUE;
          }
        }
      }
    }

    return FALSE;

#ifdef PR_USE_IPV6 
  } else if (pr_netaddr_use_ipv6() &&
             *tok == '[') {
    char *cp, *tmp;
    pr_netaddr_t *acl_addr;
    unsigned int nmaskbits;

    /* IPv6 address */

    if (pr_netaddr_get_family(session.c->remote_addr) == AF_INET) {
      /* No need to try to match an IPv6 address against an IPv4 client. */
      return FALSE;
    }

    /* Find the terminating ']'. */
    cp = strchr(tok, ']');
    if (cp == NULL) {
      wrap2_log("bad IPv6 address syntax: '%s'", tok);
      return FALSE;
    }

    *cp = '\0';

    /* Lookup a netaddr for the IPv6 address. */
    acl_addr = pr_netaddr_get_addr(wrap2_pool, tok + 1, NULL);
    if (!acl_addr) {
      wrap2_log("unable to resolve IPv6 address '%s'", tok + 1);
      return FALSE;
    }

    if (*(cp + 1) != '/') {
      wrap2_log("bad mask syntax: '%s'", cp + 1);
      return FALSE;
    }

    /* Determine the number of mask bits. */
    nmaskbits = strtol(cp + 2, &tmp, 10);
    if (tmp && *tmp) {
      wrap2_log("bad mask syntax: '%s'", tmp);
      return FALSE;
    }

    return (pr_netaddr_ncmp(session.c->remote_addr, acl_addr, nmaskbits) == 0);
#endif /* PR_USE_IPV6 */

  } else if ((mask = wrap2_strsplit(tok, '/')) != 0) {

    /* Net/mask */
    return (wrap2_match_netmask(tok, mask, wrap2_get_hostaddr(host)));

  } else {
    pr_netaddr_t *acl_addr;

    /* Anything else.
     *
     * In order to properly compare IP addresses (and to handle cases of
     * handling IPv4-mapped IPv6 addresses compared against IPv4 addresses),
     * we need to use pr_netaddr_cmp(), rather than doing the string
     * comparison that libwrap used.
     */

    acl_addr = pr_netaddr_get_addr(wrap2_pool, tok, NULL);
    if (acl_addr == NULL) {
      if (wrap2_match_string(tok, wrap2_get_hostname(host))) {
        return TRUE;
      }

      wrap2_log("unable to handle address '%s'", tok);

    } else {
      if (pr_netaddr_cmp(session.c->remote_addr, acl_addr) == 0) {
        return TRUE;
      }
    }

    if (WRAP2_IS_NOT_INADDR(tok)) {
      register unsigned int i;
      char *primary_name;
      array_header *dns_names;

      primary_name = wrap2_get_hostname(host);
      wrap2_log("comparing client hostname '%s' against DNS name '%s'",
        primary_name, tok);

      if (wrap2_match_string(tok, primary_name)) {
        return TRUE;
      }

      if (!(wrap2_opts & WRAP_OPT_CHECK_ALL_NAMES)) {
        return FALSE;
      }

      dns_names = pr_netaddr_get_dnsstr_list(session.pool,
        session.c->remote_addr);
      if (dns_names != NULL &&
          dns_names->nelts > 0) {
        char **names;

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

          name = names[i];
          if (name != NULL) {
            wrap2_log("comparing client hostname '%s' against DNS name '%s'",
              name, tok);

            if (wrap2_match_string(tok, name)) {
              return TRUE;
            }
          }
        }
      }
    }
  }

  return FALSE;
}

static unsigned char wrap2_match_client(char *tok, wrap2_conn_t *conn) {
  unsigned char match = FALSE;
  char *host = NULL;

  host = wrap2_strsplit(tok + 1, '@');
  if (host == 0) {

    /* Plain host */
    match = wrap2_match_host(tok, conn->client);

    if (match) {
      wrap2_log("client matches '%s'", tok);
    }

  } else {

    /* user@host */
    match = (wrap2_match_host(host, conn->client) &&
      wrap2_match_string(tok, wrap2_get_user(conn)));

    if (match) {
      wrap2_log("client matches '%s@%s'", tok, host);
    }
  }

  return match;
}

static unsigned char wrap2_match_daemon(char *tok, wrap2_conn_t *conn) {
  unsigned char match = FALSE;
  char *host = NULL;

  host = wrap2_strsplit(tok + 1, '@');
  if (host == 0) {

    /* Plain daemon */
    match = wrap2_match_string(tok, WRAP2_GET_DAEMON(conn));

    if (match)
      wrap2_log("daemon matches '%s'", tok);

  } else {

    /* daemon@host */
    match = (wrap2_match_string(tok, WRAP2_GET_DAEMON(conn)) &&
      wrap2_match_host(host, conn->server));

    if (match)
      wrap2_log("daemon matches '%s@%s'", tok, host);
  }

  return match;
}

static unsigned char wrap2_match_list(array_header *list, wrap2_conn_t *conn,
    unsigned char (*match_token)(char *, wrap2_conn_t *),
    unsigned int list_idx) {
  register unsigned int i;
  char **tokens = NULL;

  if (list == NULL)
    return FALSE;

  tokens = list->elts;

  /* Process tokens one at a time. We have exhausted all possible matches
   * when we reach an "EXCEPT" token or the end of the list. If we do find
   * a match, look for an "EXCEPT" list and recurse to determine whether
   * the match is affected by any exceptions.
   */

  for (i = list_idx; i < list->nelts; i++) {
    char *token;

    /* It's possible that the token string is actually NULL; handle this
     * case gracefully.
     */
    if (tokens[i] == NULL) {
      continue;
    }

    token = wrap2_skip_whitespace(tokens[i]);

    if (strcasecmp(token, "EXCEPT") == 0) {
      /* EXCEPT -- give up now. */
      return FALSE;
    }

    if (match_token(token, conn)) {
      register unsigned int j;

      /* If yes, look for exceptions */
      for (j = i + 1; j < list->nelts; j++) {
        token = wrap2_skip_whitespace(tokens[j]);
        if (strcasecmp(token, "EXCEPT") == 0) {
          return (wrap2_match_list(list, conn, match_token, j+1) == 0);
        } 
      }

      return TRUE;
    }
  }

  return FALSE;
}

#ifdef WRAP2_USE_OPTIONS

#define WRAP2_WHITESPACE		" \t\r\n"

/* Options flag for requiring a value. */
#define WRAP2_OF_NEED_ARG	(1 << 1)

/* Options flag specifying the option must be last in the list. */
#define WRAP2_OF_USE_LAST	(1 << 2)

/* Options flag allowing for optional values. */
#define WRAP2_OF_OPT_ARG	(1 << 3)

#define WRAP2_OPT_NEEDS_VAL(o)	\
  ((o)->flags & WRAP2_OF_NEED_ARG)
#define WRAP2_OPT_ALLOWS_VAL(o)	\
  ((o)->flags & (WRAP2_OF_NEED_ARG|WRAP2_OF_OPT_ARG))
#define WRAP2_OPT_NEEDS_LAST(o)	\
  ((o)->flags & WRAP2_OF_USE_LAST)

#define WRAP2_OPT_ALLOW  4
#define WRAP2_OPT_DENY   -4

/* Options routines */

static char *wrap2_opt_trim_string(char *string) {
  char *start = NULL, *end = NULL, *cp = NULL;

  for (cp = string; *cp; cp++) {
    if (!isspace((int) *cp)) {
      if (start == '\0')
        start = cp;
      end = cp;
    }
  }

  return (start ? (end[1] = '\0', start) : cp);
}

static char *wrap2_opt_get_field(array_header *opts, unsigned int *opt_idx) {
  static char *last = "";
  char *src = NULL, *dst = NULL, *res = NULL;
  char c = 0;

  char *string = ((char **) opts->elts)[*opt_idx];

  /* This function returns pointers to successive fields within a given
   * string. ":" is the field separator; warn if the rule ends in one. It
   * replaces a "\:" sequence by ":", without treating the result of
   * substitution as field terminator. A null argument means resume search
   * where the previous call terminated. This function destroys its
   * argument.
   *
   * Work from explicit source or from memory. While processing \: we
   * overwrite the input. This way we do not have to maintain buffers for
   * copies of input fields.
   */

  src = dst = res = (string ? string : last);

  if (*src == '\0')
    return NULL;

  while ((c = *src)) {
    if (c == ':') {
      if (*++src == '\0')
        wrap2_log("option rule ends in ':'");

      break;
    }

    if (c == '\\' && src[1] == ':')
      src++;
    *dst++ = *src++;
  }

  last = src;
  *dst = '\0';

  *opt_idx++;
  return res;
}

/* "allow" option - grant access */
static int wrap2_opt_allow(char *val) {
  return WRAP2_OPT_ALLOW;
}

/* "deny" option - deny access */
static int wrap2_opt_deny(char *val) {
  return WRAP2_OPT_DENY;
}

/* "nice" option - set process nice value */
static int wrap2_opt_nice(char *val) {
  int niceness = 10;
  char *tmp = NULL;

  if (val != 0) {
    niceness = (int) strtol(val, &tmp, 10);

    if (niceness < 0 || (tmp && *tmp)) {
      wrap2_log("bad nice value: '%s'", val);
      return 0;
    }
  }

  if (nice(niceness) < 0)
    wrap2_log("error handling nice option: %s", strerror(errno));

  return 0;
}

/* "setenv" option - set environment variable */
static int wrap2_opt_setenv(char *val) {
  char *value = NULL;

  if (*(value = val + strcspn(val, WRAP2_WHITESPACE)))
    *value++ = '\0';

  if (pr_env_set(session.pool, wrap2_opt_trim_string(val),
      wrap2_opt_trim_string(value)) < 0) {
    wrap2_log("error handling setenv option: %s", strerror(errno));
  }

  return 0;
}

struct wrap2_opt {
  /* Keyword name (case-insensitive) */
  char *name;

  /* Options handler */
  int (*func)(char *);

  /* Modifying flags */
  int flags;
};

static const struct wrap2_opt options_tab[] = {
  { "setenv",	wrap2_opt_setenv,	WRAP2_OF_NEED_ARG },
  { "nice",	wrap2_opt_nice,		WRAP2_OF_OPT_ARG },
  { "allow",	wrap2_opt_allow,	WRAP2_OF_USE_LAST },
  { "deny",	wrap2_opt_deny,		WRAP2_OF_USE_LAST },
  { NULL, NULL, 0 }
};

static int wrap2_handle_opts(array_header *options, wrap2_conn_t *conn) {
  char *key = NULL, *value = NULL;
  char *curr_opt = NULL, *next_opt = NULL;
  const struct wrap2_opt *opt = NULL;
  unsigned int opt_idx = 0;

  for (curr_opt = wrap2_opt_get_field(options, &opt_idx); curr_opt;
       curr_opt = next_opt) {
    int res = 0;
    next_opt = wrap2_opt_get_field(options, &opt_idx);

    /* Separate the option into name and value parts. For backwards
     * compatibility we ignore exactly one '=' between name and value.
     */
    curropt = wrap2_opt_trim_string(curr_opt);

    if (*(value = curr_opt + strcspn(curr_opt, "=" WRAP2_WHITESPACE))) {
      if (*value != '=') {
        *value++ = '\0';
        value += strspn(value, WRAP2_WHITESPACE);
      }

      if (*value == '=') {
        *value++ = '\0';
        value += strspn(value, WRAP2_WHITESPACE);
      }
    }

    if (*value == '\0')
      value = NULL;

    key = curr_opt;

    /* Disallow missing option names (and empty option fields). */
    if (*key == '\0') {
      wrap2_log("warning: missing option name");
      continue;
    }

    /* Lookup the option-specific info and do some common error checks.
     * Delegate option-specific processing to the specific functions.
     */

    /* Advance to the matching option table entry. */
    for (opt = options_tab; opt->name && strcasecmp(opt->name, key) != 0;
      opt++);

    if (opt->name == 0) {
      wrap2_log("unknown option name: '%s'", key);
      continue;
    }

    if (!value && WRAP2_OPT_NEEDS_VAL(opt)) {
      wrap2_log("option '%s' requires value", key);
      continue;
    }

    if (value && !WRAP2_OPT_ALLOWS_VAL(opt)) {
      wrap2_log("option '%s' requires no value", key);
      continue;
    }

    if (next_opt && WRAP2_OPT_NEEDS_LAST(opt)) {
      wrap2_log("option '%s' must be the last option in the list", key);
      continue;
    }

    wrap2_log("processing option: '%s %s'", key, value ? value : "");

    res = opt->func(value);
    if (res != 0)
      return res;
  }

  return 0;
}
#endif /* WRAP2_USE_OPTIONS */

#define WRAP2_TAB_ALLOW	2
#define WRAP2_TAB_MATCH	1
#define WRAP2_TAB_DENY	-1

static int wrap2_match_table(wrap2_table_t *tab, wrap2_conn_t *conn) {
  register unsigned int i;
  int res;
  array_header *daemon_list = NULL, *client_list = NULL, *options_list = NULL;

  /* Build daemon list. */
  daemon_list = tab->tab_fetch_daemons(tab, wrap2_service_name);
  if (daemon_list == NULL ||
      daemon_list->nelts == 0) {
    wrap2_log("%s", "daemon list is empty");
    return 0;
  }

  wrap2_log("table daemon list:");
  for (i = 0; i < daemon_list->nelts; i++) {
    char **daemons = daemon_list->elts;
    wrap2_log("  %s", daemons[i] ? daemons[i] : "<null>");
  }

  /* Build client list. */
  client_list = tab->tab_fetch_clients(tab, wrap2_client_name);
  if (client_list == NULL ||
      client_list->nelts == 0) {
    wrap2_log("%s", "client list is empty");
    return 0;
  }

  wrap2_log("table client list:");
  for (i = 0; i < client_list->nelts; i++) {
    char **clients = client_list->elts;
    wrap2_log("  %s", clients[i] ? clients[i] : "<null>");
  }

  /* Build options list. */
  options_list = tab->tab_fetch_options(tab, wrap2_client_name);
  if (options_list &&
      options_list->nelts > 0) {
    wrap2_log("table options list:");
    for (i = 0; i < options_list->nelts; i++) {
      char **opts = options_list->elts;
      wrap2_log("  %s", opts[i] ? opts[i] : "<null>");
    }
  }

  res = wrap2_match_list(daemon_list, conn, wrap2_match_daemon, 0);
  if (res == FALSE) {
    return 0;
  }

  res = wrap2_match_list(client_list, conn, wrap2_match_client, 0);
  if (res == FALSE) {
    return 0;
  }

#ifdef WRAP2_USE_OPTIONS
  res = wrap2_handle_opts(options_list, conn);
  if (res == WRAP2_OPT_ALLOW) {
    return WRAP2_TAB_ALLOW;
  }

  if (res == WRAP2_OPT_DENY) {
    return WRAP2_TAB_DENY;
  }
#endif

  return WRAP2_TAB_MATCH;
}

static unsigned char wrap2_allow_access(wrap2_conn_t *conn) {
  wrap2_table_t *allow_tab = NULL, *deny_tab = NULL;
  int res = 0;

  /* If the (daemon, client) pair is matched by an entry in the allow
   * table, access is granted. Otherwise, if the (daemon, client) pair is
   * matched by an entry in the deny table, access is denied. Otherwise,
   * access is granted. A non-existent access-control table is treated as an
   * empty table.
   */

  /* Open allow table. */
  allow_tab = wrap2_open_table(wrap2_allow_table);
  if (allow_tab != NULL) {

    /* Check the allow table. */
    wrap2_log("%s", "checking allow table rules");
    res = wrap2_match_table(allow_tab, conn);

    /* Close allow table. */
    wrap2_close_table(allow_tab);
    destroy_pool(allow_tab->tab_pool);
    allow_tab = NULL;

    /* No need to check the deny table if the verdict is to explicitly allow. */
    if (res == WRAP2_TAB_ALLOW ||
        res == WRAP2_TAB_MATCH) {
      wrap2_allow_table = wrap2_deny_table = NULL;
      return TRUE;
    }

    if (res == WRAP2_TAB_DENY) {
      wrap2_allow_table = wrap2_deny_table = NULL;
      return FALSE;
    }

  } else {
    wrap2_log("error opening allow table: %s", strerror(errno));
  }

  /* Open deny table. */
  deny_tab = wrap2_open_table(wrap2_deny_table);
  if (deny_tab != NULL) {

    /* Check the deny table. */
    wrap2_log("%s", "checking deny table rules");
    res = wrap2_match_table(deny_tab, conn);

    /* Close the deny table. */
    wrap2_close_table(deny_tab);
    destroy_pool(deny_tab->tab_pool);
    deny_tab = NULL;

    if (res == WRAP2_TAB_DENY ||
        res == WRAP2_TAB_MATCH) {
      wrap2_allow_table = wrap2_deny_table = NULL;
      return FALSE; 
    }

  } else {
    wrap2_log("error opening deny table: %s", strerror(errno));
  }

  wrap2_allow_table = wrap2_deny_table = NULL;
  return TRUE;
}

/* Boolean OR expression evaluation, returning TRUE if any element in the
 * expression matches, FALSE otherwise.
 */
static unsigned char wrap2_eval_or_expression(char **acl, array_header *creds) {
  unsigned char found = FALSE;
  char *elem = NULL, **list = NULL;

  if (!acl || !*acl || !creds)
    return FALSE;

  list = (char **) creds->elts;

  for (; *acl; acl++) {
    register int i = 0;
    elem = *acl;
    found = FALSE;

    if (*elem == '!') {
      found = !found;
      elem++;
    }

    for (i = 0; i < creds->nelts; i++) {
      if (strcmp(elem, "*") == 0 || (list[i] && strcmp(elem, list[i]) == 0)) {
        found = !found;
        break;
      }
    }

    if (found)
      return TRUE;
  }

  return FALSE;
}

/* Boolean AND expression evaluation, returning TRUE if every element in the
 * expression matches, FALSE otherwise.
 */
static unsigned char wrap2_eval_and_expression(char **acl, array_header *creds) {
  unsigned char found = FALSE;
  char *elem = NULL, **list = NULL;

  if (!acl || !*acl || !creds)
    return FALSE;

  list = (char **) creds->elts;

  for (; *acl; acl++) {
    register int i = 0;
    elem = *acl;
    found = FALSE;

    if (*elem == '!') {
      found = !found;
      elem++;
    }

    for (i = 0; i < creds->nelts; i++) {
      if (list[i] && strcmp(list[i], elem) == 0) {
        found = !found;
        break;
      }
    }

    if (!found) 
      return FALSE;
  }

  return TRUE;
}

int wrap2_register(const char *srcname,
    wrap2_table_t *(*srcopen)(pool *, char *)) {

  /* Note: I know that use of permanent_pool is discouraged as much as
   * possible, but in this particular instance, I need a pool that
   * persists across rehashes.
   *
   * Ideally, the wrap2_regtab_t struct would have a subpool member;
   * the objects would have their own pools which could then be
   * destroyed upon unregistration.
   */
  wrap2_regtab_t *regtab = pcalloc(permanent_pool, sizeof(wrap2_regtab_t));

  regtab->regtab_name = pstrdup(permanent_pool, srcname);
  regtab->regtab_open = srcopen;

  /* Add this object to the list. */
  if (wrap2_regtab_list) {
    wrap2_regtab_list->prev = regtab;
    regtab->next = wrap2_regtab_list;
  }

  wrap2_regtab_list = regtab;

  return 0;
}

int wrap2_unregister(const char *srcname) {
  if (wrap2_regtab_list) {
    register wrap2_regtab_t *regtab = NULL;

    for (regtab = wrap2_regtab_list; regtab; regtab = regtab->next) {
      if (strcmp(regtab->regtab_name, srcname) == 0) {

        if (regtab->prev) {
          regtab->prev->next = regtab->next;

        } else {
          wrap2_regtab_list = regtab->next;
        }

        if (regtab->next) {
          regtab->next->prev = regtab->prev;
        }

        regtab->prev = regtab->next = NULL;

        /* NOTE: a counter should be kept of the number of unregistrations,
         * as the memory for a registration is not freed on unregistration.
         */
        return 0;
      }
    }

    errno = ENOENT;
    return -1;
  }

  errno = EPERM;
  return -1;
}

/* "builtin" source callbacks. */

static int builtin_close_cb(wrap2_table_t *tab) {
  return 0;
}

static array_header *builtin_fetch_clients_cb(wrap2_table_t *tab,
    const char *name) {
  array_header *list = make_array(tab->tab_pool, 1, sizeof(char *));

  *((char **) push_array(list)) = pstrdup(tab->tab_pool, "ALL");
  return list;
}

static array_header *builtin_fetch_daemons_cb(wrap2_table_t *tab,
    const char *name) {
  array_header *list = make_array(tab->tab_pool, 1, sizeof(char *));

  *((char **) push_array(list)) = pstrdup(tab->tab_pool, name);
  return list;
}

static array_header *builtin_fetch_options_cb(wrap2_table_t *tab,
    const char *name) {
  return NULL;
}

static wrap2_table_t *builtin_open_cb(pool *parent_pool, char *srcinfo) {
  wrap2_table_t *tab = NULL;
  pool *tab_pool = make_sub_pool(parent_pool);

  /* Do not allow any parameters other than 'all. */
  if (strcasecmp(srcinfo, "all") != 0) {
    wrap2_log("error: unknown builtin parameter: '%s'", srcinfo);
    destroy_pool(tab_pool);
    errno = EINVAL;
    return NULL;
  }

  tab = (wrap2_table_t *) pcalloc(tab_pool, sizeof(wrap2_table_t));
  tab->tab_pool = tab_pool;

  tab->tab_name = "builtin";

  /* Set the necessary callbacks. */
  tab->tab_close = builtin_close_cb;
  tab->tab_fetch_clients = builtin_fetch_clients_cb;
  tab->tab_fetch_daemons = builtin_fetch_daemons_cb;
  tab->tab_fetch_options = builtin_fetch_options_cb;

  return tab;
}

/* Configuration handlers
 */

/* usage: Wrap{Allow,Deny}Msg mesg */
MODRET set_wrapmsg(cmd_rec *cmd) {
  config_rec *c = NULL;

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

  c = add_config_param_str(cmd->argv[0], 1, cmd->argv[1]);
  c->flags |= CF_MERGEDOWN;

  return PR_HANDLED(cmd);
}

/* usage: WrapEngine on|off */
MODRET set_wrapengine(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, "expecting Boolean parameter");

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

  return PR_HANDLED(cmd);
}

/* usage: WrapGroupTables group-and-expression allow-table deny-table */
MODRET set_wrapgrouptables(cmd_rec *cmd) {
  register wrap2_regtab_t *regtab = NULL;
  register unsigned int i = 0;
  unsigned char have_registration = FALSE;
  config_rec *c = NULL;

  int argc = 1;
  char **argv = NULL;
  array_header *acl = NULL;

  CHECK_ARGS(cmd, 3);
  CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON);

  /* Verify that the requested source types have been registered. */
  for (i = 2; i < cmd->argc-1; i++) {
    char *tmp = NULL;

    tmp = strchr(cmd->argv[i], ':');
    if (tmp == NULL) {
      CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "badly table parameter: '",
        cmd->argv[i], "'", NULL));
    }

    *tmp = '\0';

    for (regtab = wrap2_regtab_list; regtab; regtab = regtab->next) {
      if (strcmp(regtab->regtab_name, cmd->argv[i]) == 0) {
        have_registration = TRUE;
        break;
      }
    }

    if (!have_registration) {
      CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unsupported table source type: '",
        cmd->argv[1], "'", NULL));
    }

    *tmp = ':';
  }

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

  acl = pr_expr_create(cmd->tmp_pool, &argc, &cmd->argv[0]);

  /* Build the desired config_rec manually. */
  c->argc = argc + 2;
  c->argv = pcalloc(c->pool, (argc + 3) * sizeof(char *));
  argv = (char **) c->argv;

  /* The tables are the first two parameters */
  *argv++ = pstrdup(c->pool, cmd->argv[2]);
  *argv++ = pstrdup(c->pool, cmd->argv[3]);

  /* Now populate the group-expression names */
  if (argc && acl) {
    while (argc--) {
      *argv++ = pstrdup(c->pool, *((char **) acl->elts));
      acl->elts = ((char **) acl->elts) + 1;
    }
  }

  /* Do not forget the terminating NULL */
  *argv = NULL;

  c->flags |= CF_MERGEDOWN;
  return PR_HANDLED(cmd);
}

/* usage: WrapLog file|"none" */
MODRET set_wraplog(cmd_rec *cmd) {
  CHECK_ARGS(cmd, 1);
  CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);

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

  return PR_HANDLED(cmd);
}

/* usage: WrapOptions opt1 ... optN */
MODRET set_wrapoptions(cmd_rec *cmd) {
  config_rec *c = NULL;
  register unsigned int i = 0;
  unsigned long opts = 0UL;

  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], "CheckOnConnect") == 0) {
      opts |= WRAP_OPT_CHECK_ON_CONNECT;

    } else if (strcmp(cmd->argv[i], "CheckAllNames") == 0) {
      opts |= WRAP_OPT_CHECK_ALL_NAMES;

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

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

  return PR_HANDLED(cmd);
}

/* usage: WrapServiceName <name> */
MODRET set_wrapservicename(cmd_rec *cmd) {
  CHECK_ARGS(cmd, 1);
  CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);

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

/* usage: WrapTables allow-table deny-table */
MODRET set_wraptables(cmd_rec *cmd) {
  register wrap2_regtab_t *regtab = NULL;
  register unsigned int i = 0;
  unsigned char have_registration = FALSE;
  config_rec *c = NULL;
  
  CHECK_ARGS(cmd, 2);
  CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON);

  /* Verify that the requested source types have been registered. */
  for (i = 1; i < cmd->argc-1; i++) {
    char *tmp = NULL;

    tmp = strchr(cmd->argv[i], ':');
    if (tmp == NULL) {
      CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "badly table parameter: '",
        cmd->argv[i], "'", NULL));
    }

    *tmp = '\0';

    for (regtab = wrap2_regtab_list; regtab; regtab = regtab->next) {
      if (strcmp(regtab->regtab_name, cmd->argv[i]) == 0) {
        have_registration = TRUE;
        break;
      }
    }

    if (!have_registration) {
      CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unsupported table source type: '",
        cmd->argv[1], "'", NULL));
    }

    *tmp = ':'; 
  }

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

  return PR_HANDLED(cmd);
}

/* usage: WrapUserTables user-or-expression allow-table deny-table */
MODRET set_wrapusertables(cmd_rec *cmd) {
  register wrap2_regtab_t *regtab = NULL;
  register unsigned int i = 0;
  unsigned char have_registration = FALSE;
  config_rec *c = NULL;

  int argc = 1;
  char **argv = NULL;
  array_header *acl = NULL;

  CHECK_ARGS(cmd, 3);
  CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON);

  /* Verify that the requested source types have been registered. */
  for (i = 2; i < cmd->argc-1; i++) {
    char *tmp = NULL;

    tmp = strchr(cmd->argv[i], ':');
    if (tmp == NULL) {
      CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "badly table parameter: '",
        cmd->argv[i], "'", NULL));
    }

    *tmp = '\0';

    for (regtab = wrap2_regtab_list; regtab; regtab = regtab->next) {
      if (strcmp(regtab->regtab_name, cmd->argv[i]) == 0) {
        have_registration = TRUE;
        break;
      }
    }

    if (!have_registration) {
      CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unsupported table source type: '",
        cmd->argv[1], "'", NULL));
    }

    *tmp = ':';
  }

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

  acl = pr_expr_create(cmd->tmp_pool, &argc, &cmd->argv[0]);

  /* Build the desired config_rec manually. */
  c->argc = argc + 2;
  c->argv = pcalloc(c->pool, (argc + 3) * sizeof(char *));
  argv = (char **) c->argv;

  /* The tables are the first two parameters */
  *argv++ = pstrdup(c->pool, cmd->argv[2]);
  *argv++ = pstrdup(c->pool, cmd->argv[3]); 

  /* Now populate the user-expression names */
  if (argc && acl)
    while (argc--) {
      *argv++ = pstrdup(c->pool, *((char **) acl->elts));
      acl->elts = ((char **) acl->elts) + 1;
    }

  /* Do not forget the terminating NULL */
  *argv = NULL;

  c->flags |= CF_MERGEDOWN;

  return PR_HANDLED(cmd);
}

/* Command handlers
 */

MODRET wrap2_pre_pass(cmd_rec *cmd) {
  wrap2_conn_t conn;
  unsigned char have_tables = FALSE;
  char *user = NULL;
  config_rec *c = NULL;

  if (!wrap2_engine)
    return PR_DECLINED(cmd);

  /* Hide passwords */
  session.hide_password = TRUE;

  user = pr_table_get(session.notes, "mod_auth.orig-user", NULL);
  if (!user)
    return PR_DECLINED(cmd);

  wrap2_ctxt = pr_auth_get_anon_config(cmd->pool, &user, NULL, NULL);

  if (!user)
    return PR_DECLINED(cmd);

  {
    /* Cheat a little here, and pre-populate some of session's members.  Do
     * not worry: these values are only temporary, and will be overwritten
     * during the login process.  This needs to be done here, before the
     * call to wrap2_allow_access(), for that function does the opening of
     * the tables.
     */
    struct passwd *pw = NULL;

    pw = pr_auth_getpwnam(cmd->pool, user);
    if (pw != NULL) {
      struct group *gr = NULL;

      /* For the dir_realpath() function to work, some session members need to
       * be set.
       */
      session.user = pstrdup(cmd->pool, pw->pw_name);

      session.login_uid = pw->pw_uid;
      session.login_gid = pw->pw_gid;

      gr = pr_auth_getgrgid(cmd->pool, session.login_gid);
      if (gr != NULL) {
        session.group = pstrdup(cmd->pool, gr->gr_name);

      } else {
        wrap2_log("unable to resolve GID for '%s'", user);
      }

    } else {
      wrap2_log("unable to resolve UID for '%s'", user);
      return PR_DECLINED(cmd);
    }
  }

  /* Search first for user-specific access tables.  Multiple WrapUserTables
   * directives are allowed.
   */
  
  c = find_config(wrap2_ctxt ? wrap2_ctxt->subset : main_server->conf,
    CONF_PARAM, "WrapUserTables", FALSE);
  while (c) {
    array_header *user_array;

    pr_signals_handle();

    user_array = make_array(cmd->tmp_pool, 0, sizeof(char *));
    *((char **) push_array(user_array)) = pstrdup(cmd->tmp_pool, user);

    /* Check the user OR expression. Do not forget the offset, to skip
     * the table name strings in c->argv.
     */
    if (wrap2_eval_or_expression((char **) &c->argv[2], user_array)) {
      wrap2_log("matched WrapUserTables expression for user '%s'", user);

      wrap2_allow_table = c->argv[0];
      wrap2_deny_table = c->argv[1];
      wrap2_client_name = session.user;

      have_tables = TRUE;
      c = NULL;

      break;
    }

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

  /* Next, search for group-specific access tables.  Multiple WrapGroupTables
   * directives are allowed.
   */ 
  if (!have_tables) {
    c = find_config(wrap2_ctxt ? wrap2_ctxt->subset : main_server->conf,
      CONF_PARAM, "WrapGroupTables", FALSE);
  }

  while (c) {
    array_header *gid_array, *group_array;

    pr_signals_handle();

    gid_array = make_array(cmd->pool, 0, sizeof(gid_t));
    group_array = make_array(cmd->pool, 0, sizeof(char *));

    if (pr_auth_getgroups(cmd->pool, user, &gid_array, &group_array) < 1) {
      wrap2_log("no supplemental groups found for user '%s'", user);

    } else {

      /* Check the group AND expression.  Do not forget the offset, to skip
       * the table names strings in c->argv.
       */
      if (wrap2_eval_and_expression((char **) &c->argv[2], group_array)) {
        wrap2_log("matched WrapGroupTables expression for user '%s'", user);

        wrap2_allow_table = c->argv[0];
        wrap2_deny_table = c->argv[1];
        wrap2_client_name = session.group;

        have_tables = TRUE;
        c = NULL;

        break;
      }
    }

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

  /* Finally for globally-applicable access files.  Only one such directive
   * is allowed.
   */
  if (!have_tables) {
    c = find_config(wrap2_ctxt ? wrap2_ctxt->subset : main_server->conf,
      CONF_PARAM, "WrapTables", FALSE);
  }

  if (c) {
    wrap2_allow_table = c->argv[0];
    wrap2_deny_table = c->argv[1];

    wrap2_client_name = "";
    have_tables = TRUE;
  }

  if (have_tables) {
    /* Log the names of the allow/deny tables being used. */
    wrap2_log("using '%s' for allow table", wrap2_allow_table);
    wrap2_log("using '%s' for deny table", wrap2_deny_table);

  } else {
    wrap2_log("no tables configured, allowing connection");
    return PR_DECLINED(cmd);
  }

  wrap2_log("looking under service name '%s'", wrap2_service_name);

  memset(&conn, '\0', sizeof(conn));

  wrap2_conn_set(&conn, WRAP2_CONN_DAEMON, wrap2_service_name,
    WRAP2_CONN_SOCK_FD, session.c->rfd, 0);

  wrap2_log("%s", "checking access rules for connection");

  if (strcasecmp(wrap2_get_hostname(conn.client), WRAP2_PARANOID) == 0 ||
      !wrap2_allow_access(&conn)) {
    char *msg = NULL;

    /* Log the denied connection */
    wrap2_log("refused connection from %s", wrap2_get_client(&conn));

    /* Broadcast this event to any interested listeners.  We use the same
     * event name as mod_wrap for consistency.
     */
    pr_event_generate("mod_wrap.connection-denied", NULL);

    /* Check for a configured WrapDenyMsg.  If not present, then use the
     * default denied message.
     */
    msg = get_param_ptr(wrap2_ctxt ? wrap2_ctxt->subset : main_server->conf,
      "WrapDenyMsg", FALSE);
    if (msg != NULL) {
      msg = sreplace(cmd->tmp_pool, msg, "%u", user, NULL);
    }

    pr_response_send(R_530, "%s", msg ? msg : _("Access denied"));
    pr_session_disconnect(&wrap2_module, PR_SESS_DISCONNECT_MODULE_ACL, NULL);
  }

  wrap2_log("allowed connection from %s", wrap2_get_client(&conn));
  return PR_DECLINED(cmd);
}

MODRET wrap2_post_pass(cmd_rec *cmd) {
  char *msg = NULL;

  if (!wrap2_engine)
    return PR_DECLINED(cmd);

  /* Check for a configured WrapAllowMsg.  If the connection were denied,
   * it would have been terminated before reaching this command handler.
   */
  msg = get_param_ptr(wrap2_ctxt ? wrap2_ctxt->subset : main_server->conf,
    "WrapAllowMsg", FALSE);
  if (msg != NULL) {
    char *user;

    user = pr_table_get(session.notes, "mod_auth.orig-user", NULL);
    msg = sreplace(cmd->tmp_pool, msg, "%u", user, NULL);
    pr_response_add(R_DUP, "%s", msg);
  }

  return PR_DECLINED(cmd);
}

MODRET wrap2_post_pass_err(cmd_rec *cmd) {
  if (!wrap2_engine)
    return PR_DECLINED(cmd);

  wrap2_ctxt = NULL;
  wrap2_allow_table = NULL;
  wrap2_deny_table = NULL;
  wrap2_client_name = NULL;

  return PR_DECLINED(cmd);
}

/* Event handlers
 */

static void wrap2_exit_ev(const void *event_data, void *user_data) {
  wrap2_closelog();
  return;
}

#if defined(PR_SHARED_MODULE)
static void wrap2_mod_unload_ev(const void *event_data, void *user_data) {
  if (strcmp("mod_wrap2.c", (const char *) event_data) == 0) {
    /* Unregister ourselves from all events. */
    pr_event_unregister(&wrap2_module, NULL, NULL);

    wrap2_unregister("builtin");

    if (wrap2_pool) {
      destroy_pool(wrap2_pool);
      wrap2_pool = NULL;
    }

    close(wrap2_logfd);
    wrap2_logfd = -1;
  }
}

#endif /* PR_SHARED_MODULE */

static void wrap2_restart_ev(const void *event_data, void *user_data) {

  /* Bounce the log file descriptor. */
  wrap2_closelog();
  wrap2_openlog();

  /* Reset the module's memory pool. */
  destroy_pool(wrap2_pool);
  wrap2_pool = make_sub_pool(permanent_pool);
  pr_pool_tag(wrap2_pool, MOD_WRAP2_VERSION);
}

/* Initialization routines
 */

static int wrap2_init(void) {

  /* Initialize the module's memory pool. */
  if (!wrap2_pool) {
    wrap2_pool = make_sub_pool(permanent_pool);
    pr_pool_tag(wrap2_pool, MOD_WRAP2_VERSION);
  }

#if defined(PR_SHARED_MODULE)
  pr_event_register(&wrap2_module, "core.module-unload", wrap2_mod_unload_ev,
    NULL);
#endif /* PR_SHARED_MODULE */
  pr_event_register(&wrap2_module, "core.restart", wrap2_restart_ev, NULL);

  /* Initialize the source object for type "builtin". */
  wrap2_register("builtin", builtin_open_cb);

  return 0;
}

static int wrap2_sess_init(void) {
  config_rec *c;

  c = find_config(main_server->conf, CONF_PARAM, "WrapEngine", FALSE);
  if (c) {
    wrap2_engine = *((int *) c->argv[0]);
  }

  if (!wrap2_engine) {
    return 0;
  }

  wrap2_openlog();

  /* Look up any configured WrapServiceName */
  wrap2_service_name = get_param_ptr(main_server->conf, "WrapServiceName",
    FALSE);
  if (wrap2_service_name == NULL)
    wrap2_service_name = WRAP2_DEFAULT_SERVICE_NAME;

  /* Make sure that tables will be closed when the child exits. */
  pr_event_register(&wrap2_module, "core.exit", wrap2_exit_ev, NULL);

  c = find_config(main_server->conf, CONF_PARAM, "WrapOptions", FALSE);
  if (c) {
    wrap2_opts = *((unsigned long *) c->argv[0]);
  }

  if (wrap2_opts & WRAP_OPT_CHECK_ON_CONNECT) {
    c = find_config(main_server->conf, CONF_PARAM, "WrapTables", FALSE);
    if (c) {
      wrap2_conn_t conn;

      wrap2_allow_table = c->argv[0];
      wrap2_deny_table = c->argv[1];
      wrap2_client_name = "";

      wrap2_log("using '%s' for allow table", wrap2_allow_table);
      wrap2_log("using '%s' for deny table", wrap2_deny_table);
      wrap2_log("looking under service name '%s'", wrap2_service_name);

      memset(&conn, '\0', sizeof(conn));
      wrap2_conn_set(&conn, WRAP2_CONN_DAEMON, wrap2_service_name,
        WRAP2_CONN_SOCK_FD, session.c->rfd, 0);

      wrap2_log("%s", "checking access rules for connection");

      if (strcasecmp(wrap2_get_hostname(conn.client), WRAP2_PARANOID) == 0 ||
          !wrap2_allow_access(&conn)) {
        char *msg = NULL;

        /* Log the denied connection */
        wrap2_log("refused connection from %s", wrap2_get_client(&conn));

        /* Broadcast this event to any interested listeners.  We use the same
         * event name as mod_wrap for consistency.
         */
        pr_event_generate("mod_wrap.connection-denied", NULL);

        /* Check for a configured WrapDenyMsg.  If not present, then use the
         * default denied message.
         */
        msg = get_param_ptr(main_server->conf, "WrapDenyMsg", FALSE);
        if (msg != NULL) {
          msg = sreplace(session.pool, msg, "%u", "unknown", NULL);
        }

        pr_response_send(R_530, "%s", msg ? msg : _("Access denied"));
        pr_session_disconnect(&wrap2_module, PR_SESS_DISCONNECT_MODULE_ACL,
          NULL);
      }
    }
  }

  return 0;
}

/* Module API tables
 */

static conftable wrap2_conftab[] = {
  { "WrapAllowMsg",		set_wrapmsg,		NULL },
  { "WrapDenyMsg",		set_wrapmsg,		NULL },
  { "WrapEngine",		set_wrapengine,		NULL },
  { "WrapGroupTables",		set_wrapgrouptables,	NULL },
  { "WrapLog",			set_wraplog,		NULL },
  { "WrapOptions",		set_wrapoptions,	NULL },
  { "WrapServiceName",		set_wrapservicename,	NULL },
  { "WrapTables",		set_wraptables,		NULL },
  { "WrapUserTables",		set_wrapusertables,	NULL },
  { NULL }
};

static cmdtable wrap2_cmdtab[] = {
  { PRE_CMD,	C_PASS,	G_NONE,	wrap2_pre_pass,		FALSE,	FALSE },
  { POST_CMD,	C_PASS,	G_NONE,	wrap2_post_pass,	FALSE,	FALSE },
  { POST_CMD_ERR,C_PASS,G_NONE,	wrap2_post_pass_err,	FALSE,	FALSE },
  { 0, NULL }
};

module wrap2_module = {
  NULL, NULL,

  /* Module API version 2.0 */
  0x20,

  /* Module name */
  "wrap2",

  /* Mmodule configuration handler table */
  wrap2_conftab,

  /* Module command handler table */
  wrap2_cmdtab,

  /* Module authentication handler table */
  NULL,

  /* Module initialization */
  wrap2_init,

  /* Session initialization */
  wrap2_sess_init,

  /* Module version */
  MOD_WRAP2_VERSION
};