summaryrefslogtreecommitdiffstats
path: root/source4/scripting/python/samba/netcmd/testparm.py
blob: a6639a3d045c33ce6d57d44bf92f2d1da23a017b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
#   Unix SMB/CIFS implementation.
#   Test validity of smb.conf
#   Copyright (C) 2010-2011 Jelmer Vernooij <jelmer@samba.org>
#
# Based on the original in C:
#   Copyright (C) Karl Auer 1993, 1994-1998
#   Extensively modified by Andrew Tridgell, 1995
#   Converted to popt by Jelmer Vernooij (jelmer@nl.linux.org), 2002
#   Updated for Samba4 by Andrew Bartlett <abartlet@samba.org> 2006
#
# 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 3 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, see <http://www.gnu.org/licenses/>.
#
# Testbed for loadparm.c/params.c
#
# This module simply loads a specified configuration file and
# if successful, dumps it's contents to stdout. Note that the
# operation is performed with DEBUGLEVEL at 3.
#
# Useful for a quick 'syntax check' of a configuration file.
#

import os
import sys

import samba
import samba.getopt as options
from samba.netcmd import Command, CommandError, Option

class cmd_testparm(Command):
    """Syntax check the configuration file."""

    synopsis = "%prog [options]"

    takes_optiongroups = {
        "sambaopts" : options.SambaOptions,
        "versionopts": options.VersionOptions
    }

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions
    }

    takes_options = [
        Option("--section-name", type=str,
               help="Limit testparm to a named section"),
        Option("--parameter-name", type=str,
               help="Limit testparm to a named parameter"),
        Option("--client-name", type=str,
               help="Client DNS name for 'hosts allow' checking "
                    "(should match reverse lookup)"),
        Option("--client-ip", type=str,
               help="Client IP address for 'hosts allow' checking"),
        Option("--suppress-prompt", action="store_true", default=False,
               help="Suppress prompt for enter"),
        Option("-v", "--verbose", action="store_true",
               default=False, help="Show default options too"),
        # We need support for smb.conf macros before this will work again
        Option("--server", type=str, help="Set %%L macro to servername"),
        # These are harder to do with the new code structure
        Option("--show-all-parameters", action="store_true", default=False,
               help="Show the parameters, type, possible values")
        ]

    takes_args = []

    def run(self, sambaopts, versionopts, 
            section_name=None, parameter_name=None,
            client_ip=None, client_name=None, verbose=False,
            suppress_prompt=None,
            show_all_parameters=False, server=None):
        if server:
            raise NotImplementedError("--server not yet implemented")
        if show_all_parameters:
            raise NotImplementedError("--show-all-parameters not yet implemented")
        if client_name is not None and client_ip is None:
            raise CommandError("Both a DNS name and an IP address are "
                               "required for the host access check")

        lp = sambaopts.get_loadparm()

        # We need this to force the output
        samba.set_debug_level(2)

        logger = self.get_logger("testparm")

        logger.info("Loaded smb config files from %s", lp.configfile)
        logger.info("Loaded services file OK.")

        valid = self.do_global_checks(lp, logger)
        valid = valid and self.do_share_checks(lp, logger)
        if client_name is not None and client_ip is not None:
            self.check_client_access(lp, logger, client_name, client_ip)
        else:
            if section_name is not None or parameter_name is not None:
                if parameter_name is None:
                    lp[section_name].dump(sys.stdout, lp.default_service, verbose)
                else:
                    self.outf.write(lp.get(parameter_name, section_name)+"\n")
            else:
                if not suppress_prompt:
                    self.outf.write("Press enter to see a dump of your service definitions\n")
                    sys.stdin.readline()
                lp.dump(sys.stdout, verbose)
        if valid:
            return
        else:
            raise CommandError("Invalid smb.conf")

    def do_global_checks(self, lp, logger):
        valid = True

        netbios_name = lp.get("netbios name")
        if not samba.valid_netbios_name(netbios_name):
            logger.error("netbios name %s is not a valid netbios name",
                         netbios_name)
            valid = False

        workgroup = lp.get("workgroup")
        if not samba.valid_netbios_name(workgroup):
            logger.error("workgroup name %s is not a valid netbios name",
                         workgroup)
            valid = False

        lockdir = lp.get("lockdir")

        if not os.path.isdir(lockdir):
            logger.error("lock directory %s does not exist", lockdir)
            valid = False

        piddir = lp.get("pid directory")

        if not os.path.isdir(piddir):
            logger.error("pid directory %s does not exist", piddir)
            valid = False

        winbind_separator = lp.get("winbind separator")

        if len(winbind_separator) != 1:
            logger.error("the 'winbind separator' parameter must be a single "
                         "character.")
            valid = False

        if winbind_separator == '+':
            logger.error("'winbind separator = +' might cause problems with group "
                         "membership.")
            valid = False

        return valid

    def allow_access(self, deny_list, allow_list, cname, caddr):
        raise NotImplementedError(self.allow_access)

    def do_share_checks(self, lp, logger):
        valid = True
        for s in lp.services():
            if len(s) > 12:
                logger.warning("You have some share names that are longer than 12 "
                    "characters. These may not be accessible to some older "
                    "clients. (Eg. Windows9x, WindowsMe, and not listed in "
                    "smbclient in Samba 3.0.)")
                break

        for s in lp.services():
            deny_list = lp.get("hosts deny", s)
            allow_list = lp.get("hosts allow", s)
            if deny_list:
                for entry in deny_list:
                    if "*" in entry or "?" in entry:
                        logger.error("Invalid character (* or ?) in hosts deny "
                                     "list (%s) for service %s.", entry, s)
                        valid = False

            if allow_list:
                for entry in allow_list:
                    if "*" in entry or "?" in entry:
                        logger.error("Invalid character (* or ?) in hosts allow "
                                     "list (%s) for service %s.", entry, s)
                        valid = False
        return valid

    def check_client_access(self, lp, logger, cname, caddr):
        # this is totally ugly, a real `quick' hack
        for s in lp.services():
            if (self.allow_access(lp.get("hosts deny"), lp.get("hosts allow"), cname,
                             caddr) and
                self.allow_access(lp.get("hosts deny", s), lp.get("hosts allow", s),
                             cname, caddr)):
                logger.info("Allow connection from %s (%s) to %s", cname, caddr, s)
            else:
                logger.info("Deny connection from %s (%s) to %s", cname, caddr, s)

##   FIXME: We need support for smb.conf macros before this will work again
##
##    if (new_local_machine) {
##        set_local_machine_name(new_local_machine, True)
##    }
#
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 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482
/*
 *  OpenVPN -- An application to securely tunnel IP networks
 *             over a single TCP/UDP port, with support for SSL/TLS-based
 *             session authentication and key exchange,
 *             packet encryption, packet authentication, and
 *             packet compression.
 *
 *  Copyright (C) 2002-2005 OpenVPN Solutions LLC <info@openvpn.net>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License version 2
 *  as published by the Free Software Foundation.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program (see the file COPYING included with this
 *  distribution); if not, write to the Free Software Foundation, Inc.,
 *  59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#ifdef WIN32
#include "config-win32.h"
#else
#include "config.h"
#endif

#include "syshead.h"

#ifdef ENABLE_MANAGEMENT

#include "error.h"
#include "fdmisc.h"
#include "options.h"
#include "sig.h"
#include "event.h"
#include "otime.h"
#include "integer.h"
#include "misc.h"
#include "ssl.h"
#include "manage.h"

#include "memdbg.h"

#define MANAGEMENT_ECHO_PULL_INFO 0

#if MANAGEMENT_ECHO_PULL_INFO
#define MANAGEMENT_ECHO_FLAGS LOG_PRINT_INTVAL
#else
#define MANAGEMENT_ECHO_FLAGS 0
#endif

/* tag for blank username/password */
static const char blank_up[] = "[[BLANK]]";

struct management *management; /* GLOBAL */

/* static forward declarations */
static void man_output_standalone (struct management *man, volatile int *signal_received);
static void man_reset_client_socket (struct management *man, const bool exiting);

static void
man_help ()
{
  msg (M_CLIENT, "Management Interface for %s", title_string);
  msg (M_CLIENT, "Commands:");
  msg (M_CLIENT, "auth-retry t           : Auth failure retry mode (none,interact,nointeract).");
  msg (M_CLIENT, "bytecount n            : Show bytes in/out, update every n secs (0=off).");
  msg (M_CLIENT, "echo [on|off] [N|all]  : Like log, but only show messages in echo buffer.");
  msg (M_CLIENT, "exit|quit              : Close management session.");
  msg (M_CLIENT, "forget-passwords       : Forget passwords entered so far.");
  msg (M_CLIENT, "help                   : Print this message.");
  msg (M_CLIENT, "hold [on|off|release]  : Set/show hold flag to on/off state, or"); 
  msg (M_CLIENT, "                         release current hold and start tunnel."); 
  msg (M_CLIENT, "kill cn                : Kill the client instance(s) having common name cn.");
  msg (M_CLIENT, "kill IP:port           : Kill the client instance connecting from IP:port.");
  msg (M_CLIENT, "log [on|off] [N|all]   : Turn on/off realtime log display");
  msg (M_CLIENT, "                         + show last N lines or 'all' for entire history.");
  msg (M_CLIENT, "mute [n]               : Set log mute level to n, or show level if n is absent.");
  msg (M_CLIENT, "needok type action     : Enter confirmation for NEED-OK request of 'type',");
  msg (M_CLIENT, "                         where action = 'ok' or 'cancel'.");
  msg (M_CLIENT, "net                    : (Windows only) Show network info and routing table.");
  msg (M_CLIENT, "password type p        : Enter password p for a queried OpenVPN password.");
  msg (M_CLIENT, "signal s               : Send signal s to daemon,");
  msg (M_CLIENT, "                         s = SIGHUP|SIGTERM|SIGUSR1|SIGUSR2.");
  msg (M_CLIENT, "state [on|off] [N|all] : Like log, but show state history.");
  msg (M_CLIENT, "status [n]             : Show current daemon status info using format #n.");
  msg (M_CLIENT, "test n                 : Produce n lines of output for testing/debugging.");
  msg (M_CLIENT, "username type u        : Enter username u for a queried OpenVPN username.");
  msg (M_CLIENT, "verb [n]               : Set log verbosity level to n, or show if n is absent.");
  msg (M_CLIENT, "version                : Show current version number.");
  msg (M_CLIENT, "END");
}

static const char *
man_state_name (const int state)
{
  switch (state)
    {
    case OPENVPN_STATE_INITIAL:
      return "INITIAL";
    case OPENVPN_STATE_CONNECTING:
      return "CONNECTING";
    case OPENVPN_STATE_WAIT:
      return "WAIT";
    case OPENVPN_STATE_AUTH:
      return "AUTH";
    case OPENVPN_STATE_GET_CONFIG:
      return "GET_CONFIG";
    case OPENVPN_STATE_ASSIGN_IP:
      return "ASSIGN_IP";
    case OPENVPN_STATE_ADD_ROUTES:
      return "ADD_ROUTES";
    case OPENVPN_STATE_CONNECTED:
      return "CONNECTED";
    case OPENVPN_STATE_RECONNECTING:
      return "RECONNECTING";
    case OPENVPN_STATE_EXITING:
      return "EXITING";
    case OPENVPN_STATE_RESOLVE:
      return "RESOLVE";
    case OPENVPN_STATE_TCP_CONNECT:
      return "TCP_CONNECT";
    default:
      return "?";
    }
}

static void
man_welcome (struct management *man)
{
  msg (M_CLIENT, ">INFO:OpenVPN Management Interface Version %d -- type 'help' for more info",
       MANAGEMENT_VERSION);
  if (man->persist.special_state_msg)
    msg (M_CLIENT, "%s", man->persist.special_state_msg);
}

static inline bool
man_password_needed (struct management *man)
{
  return man->settings.up.defined && !man->connection.password_verified;
}

static void
man_check_password (struct management *man, const char *line)
{
  if (man_password_needed (man))
    {
      if (streq (line, man->settings.up.password))
	{
	  man->connection.password_verified = true;
	  msg (M_CLIENT, "SUCCESS: password is correct");
	  man_welcome (man);
	}
      else
	{
	  man->connection.password_verified = false;
	  msg (M_CLIENT, "ERROR: bad password");
	  if (++man->connection.password_tries >= MANAGEMENT_N_PASSWORD_RETRIES)
	    {
	      msg (M_WARN, "MAN: client connection rejected after %d failed password attempts",
		   MANAGEMENT_N_PASSWORD_RETRIES);
	      man->connection.halt = true;
	    }
	}
    }
}

static void
man_update_io_state (struct management *man)
{
  if (socket_defined (man->connection.sd_cli))
    {
      if (output_list_defined (man->connection.out))
	{
	  man->connection.state = MS_CC_WAIT_WRITE;
	}
      else
	{
	  man->connection.state = MS_CC_WAIT_READ;
	}
    }
}

static void
man_output_list_push (struct management *man, const char *str)
{
  if (management_connected (man))
    {
      if (str)
	output_list_push (man->connection.out, (const unsigned char *) str);
      man_update_io_state (man);
      if (!man->persist.standalone_disabled)
	{
	  volatile int signal_received = 0;
	  man_output_standalone (man, &signal_received);
	}
    }
}

static void
man_prompt (struct management *man)
{
  if (man_password_needed (man))
    man_output_list_push (man, "ENTER PASSWORD:");
#if 0 /* should we use prompt? */
  else
    man_output_list_push (man, PACKAGE_NAME ">");
#endif
}

static void
man_close_socket (struct management *man, const socket_descriptor_t sd)
{
#ifndef WIN32
  /*
   * Windows doesn't need this because the ne32 event is permanently
   * enabled at struct management scope.
   */
  if (man->persist.callback.delete_event)
    (*man->persist.callback.delete_event) (man->persist.callback.arg, sd);
#endif
  openvpn_close_socket (sd);
}

static void
virtual_output_callback_func (void *arg, const unsigned int flags, const char *str)
{
  static int recursive_level = 0; /* GLOBAL */

  if (!recursive_level) /* don't allow recursion */
    {
      struct gc_arena gc = gc_new ();
      struct management *man = (struct management *) arg;
      struct log_entry e;
      const char *out = NULL;

      ++recursive_level;

      CLEAR (e);
      update_time ();
      e.timestamp = now;
      e.u.msg_flags = flags;
      e.string = str;

      if (flags & M_FATAL)
	man->persist.standalone_disabled = false;

      if (flags != M_CLIENT)
	log_history_add (man->persist.log, &e);

      if (!man_password_needed (man))
	{
	  if (flags == M_CLIENT)
	    out = log_entry_print (&e, LOG_PRINT_CRLF, &gc);
	  else if (man->connection.log_realtime)
	    out = log_entry_print (&e, LOG_PRINT_INT_DATE
				   |   LOG_PRINT_MSG_FLAGS
				   |   LOG_PRINT_LOG_PREFIX
				   |   LOG_PRINT_CRLF, &gc);
	  if (out)
	    man_output_list_push (man, out);
	  if (flags & M_FATAL)
	    {
	      out = log_entry_print (&e, LOG_FATAL_NOTIFY|LOG_PRINT_CRLF, &gc);
	      if (out)
		{
		  man_output_list_push (man, out);
		  man_reset_client_socket (man, true);
		}
	    }
	}

      --recursive_level;
      gc_free (&gc);
    }
}

/*
 * Given a signal, return the signal with possible remapping applied,
 * or -1 if the signal should be ignored.
 */
static int
man_mod_signal (const struct management *man, const int signum)
{
  const unsigned int flags = man->settings.mansig;
  int s = signum;
  if (s == SIGUSR1)
    {
      if (flags & MANSIG_MAP_USR1_TO_HUP)
	s = SIGHUP;
      if (flags & MANSIG_MAP_USR1_TO_TERM)
	s = SIGTERM;
    }
  if (flags & MANSIG_IGNORE_USR1_HUP)
    {
      if (s == SIGHUP || s == SIGUSR1)
	s = -1;
    }
  return s;
}

static void
man_signal (struct management *man, const char *name)
{
  const int sig = parse_signal (name);
  if (sig >= 0)
    {
      const int sig_mod = man_mod_signal (man, sig);
      if (sig_mod >= 0)
	{
	  throw_signal (sig_mod);
	  msg (M_CLIENT, "SUCCESS: signal %s thrown", signal_name (sig_mod, true));
	}
      else
	{
	  if (man->persist.special_state_msg)
	    msg (M_CLIENT, "%s", man->persist.special_state_msg);
	  else
	    msg (M_CLIENT, "ERROR: signal '%s' is currently ignored", name);
	}
    }
  else
    {
      msg (M_CLIENT, "ERROR: signal '%s' is not a known signal type", name);
    }
}

static void
man_status (struct management *man, const int version, struct status_output *so)
{
  if (man->persist.callback.status)
    {
      (*man->persist.callback.status) (man->persist.callback.arg, version, so);
    }
  else
    {
      msg (M_CLIENT, "ERROR: The 'status' command is not supported by the current daemon mode");
    }
}

static void
man_bytecount (struct management *man, const int update_seconds)
{
  man->connection.bytecount_update_seconds = update_seconds;
}

void
man_bytecount_output (struct management *man)
{
  char in[32];
  char out[32];
  /* do in a roundabout way to work around possible mingw or mingw-glibc bug */
  openvpn_snprintf (in, sizeof (in), counter_format, man->persist.bytes_in);
  openvpn_snprintf (out, sizeof (out), counter_format, man->persist.bytes_out);
  msg (M_CLIENT, ">BYTECOUNT:%s,%s", in, out);
  man->connection.bytecount_last_update = now;
}

static void
man_kill (struct management *man, const char *victim)
{
  struct gc_arena gc = gc_new ();

  if (man->persist.callback.kill_by_cn && man->persist.callback.kill_by_addr)
    {
      struct buffer buf;
      char p1[128];
      char p2[128];
      int n_killed;

      buf_set_read (&buf, (uint8_t*) victim, strlen (victim) + 1);
      buf_parse (&buf, ':', p1, sizeof (p1));
      buf_parse (&buf, ':', p2, sizeof (p2));

      if (strlen (p1) && strlen (p2))
	{
	  /* IP:port specified */
	  bool status;
	  const in_addr_t addr = getaddr (GETADDR_HOST_ORDER|GETADDR_MSG_VIRT_OUT, p1, 0, &status, NULL);
	  if (status)
	    {
	      const int port = atoi (p2);
	      if (port > 0 && port < 65536)
		{
		  n_killed = (*man->persist.callback.kill_by_addr) (man->persist.callback.arg, addr, port);
		  if (n_killed > 0)
		    {
		      msg (M_CLIENT, "SUCCESS: %d client(s) at address %s:%d killed",
			   n_killed,
			   print_in_addr_t (addr, 0, &gc),
			   port);
		    }
		  else
		    {
		      msg (M_CLIENT, "ERROR: client at address %s:%d not found",
			   print_in_addr_t (addr, 0, &gc),
			   port);
		    }
		}
	      else
		{
		  msg (M_CLIENT, "ERROR: port number is out of range: %s", p2);
		}
	    }
	  else
	    {
	      msg (M_CLIENT, "ERROR: error parsing IP address: %s", p1);
	    }
	}
      else if (strlen (p1))
	{
	  /* common name specified */
	  n_killed = (*man->persist.callback.kill_by_cn) (man->persist.callback.arg, p1);
	  if (n_killed > 0)
	    {
	      msg (M_CLIENT, "SUCCESS: common name '%s' found, %d client(s) killed", p1, n_killed);
	    }
	  else
	    {
	      msg (M_CLIENT, "ERROR: common name '%s' not found", p1);
	    }
	}
      else
	{
	  msg (M_CLIENT, "ERROR: kill parse");
	}
    }
  else
    {
      msg (M_CLIENT, "ERROR: The 'kill' command is not supported by the current daemon mode");
    }

  gc_free (&gc);
}

/*
 * General-purpose history command handler
 * for the log and echo commands.
 */
static void
man_history (struct management *man,
	     const char *parm,
	     const char *type,
	     struct log_history *log,
	     bool *realtime,
	     const unsigned int lep_flags)
{
  struct gc_arena gc = gc_new ();
  int n = 0;

  if (streq (parm, "on"))
    {
      *realtime = true;
      msg (M_CLIENT, "SUCCESS: real-time %s notification set to ON", type);
    }
  else if (streq (parm, "off"))
    {
      *realtime = false;
      msg (M_CLIENT, "SUCCESS: real-time %s notification set to OFF", type);
    }
  else if (streq (parm, "all") || (n = atoi (parm)) > 0)
    {
      const int size = log_history_size (log);
      const int start = (n ? n : size) - 1;
      int i;

      for (i = start; i >= 0; --i)
	{
	  const struct log_entry *e = log_history_ref (log, i);
	  if (e)
	    {
	      const char *out = log_entry_print (e, lep_flags, &gc);
	      virtual_output_callback_func (man, M_CLIENT, out);
	    }
	}
      msg (M_CLIENT, "END");
    }
  else
    {
      msg (M_CLIENT, "ERROR: %s parameter must be 'on' or 'off' or some number n or 'all'", type);
    }

  gc_free (&gc);
}

static void
man_log (struct management *man, const char *parm)
{
  man_history (man,
	       parm,
	       "log",
	       man->persist.log,
	       &man->connection.log_realtime,
	       LOG_PRINT_INT_DATE|LOG_PRINT_MSG_FLAGS);
}

static void
man_echo (struct management *man, const char *parm)
{
  man_history (man,
	       parm,
	       "echo",
	       man->persist.echo,
	       &man->connection.echo_realtime,
	       LOG_PRINT_INT_DATE|MANAGEMENT_ECHO_FLAGS);
}

static void
man_state (struct management *man, const char *parm)
{
  man_history (man,
	       parm,
	       "state",
	       man->persist.state,
	       &man->connection.state_realtime,
	       LOG_PRINT_INT_DATE|LOG_PRINT_STATE|
	       LOG_PRINT_LOCAL_IP|LOG_PRINT_REMOTE_IP);
}

static void
man_up_finalize (struct management *man)
{
  switch (man->connection.up_query_mode)
    {
    case UP_QUERY_DISABLED:
      man->connection.up_query.defined = false;
      break;
    case UP_QUERY_USER_PASS:
      if (strlen (man->connection.up_query.username) && strlen (man->connection.up_query.password))
	man->connection.up_query.defined = true;
      break;
    case UP_QUERY_PASS:
      if (strlen (man->connection.up_query.password))
	man->connection.up_query.defined = true;
      break;
    case UP_QUERY_NEED_OK:
      if (strlen (man->connection.up_query.password))
	man->connection.up_query.defined = true;
      break;
    default:
      ASSERT (0);
    }
}

static void
man_query_user_pass (struct management *man,
		     const char *type,
		     const char *string,
		     const bool needed,
		     const char *prompt,
		     char *dest,
		     int len)
{
  if (needed)
    {
      ASSERT (man->connection.up_query_type);
      if (streq (man->connection.up_query_type, type))
	{
	  strncpynt (dest, string, len);
	  man_up_finalize (man);
	  msg (M_CLIENT, "SUCCESS: '%s' %s entered, but not yet verified",
	       type,
	       prompt);
	}
      else
	msg (M_CLIENT, "ERROR: %s of type '%s' entered, but we need one of type '%s'",
	     prompt,
	     type,
	     man->connection.up_query_type);
    }
  else
    {
      msg (M_CLIENT, "ERROR: no %s is currently needed at this time", prompt);
    }
}

static void
man_query_username (struct management *man, const char *type, const char *string)
{
  const bool needed = (man->connection.up_query_mode == UP_QUERY_USER_PASS && man->connection.up_query_type);
  man_query_user_pass (man, type, string, needed, "username", man->connection.up_query.username, USER_PASS_LEN);
}

static void
man_query_password (struct management *man, const char *type, const char *string)
{
  const bool needed = ((man->connection.up_query_mode == UP_QUERY_USER_PASS
			|| man->connection.up_query_mode == UP_QUERY_PASS)
		       && man->connection.up_query_type);
  if (!string[0]) /* allow blank passwords to be passed through using the blank_up tag */
    string = blank_up;
  man_query_user_pass (man, type, string, needed, "password", man->connection.up_query.password, USER_PASS_LEN);
}

static void
man_query_need_ok (struct management *man, const char *type, const char *action)
{
  const bool needed = ((man->connection.up_query_mode == UP_QUERY_NEED_OK) && man->connection.up_query_type);
  man_query_user_pass (man, type, action, needed, "needok-confirmation", man->connection.up_query.password, USER_PASS_LEN);
}

static void
man_forget_passwords (struct management *man)
{
  ssl_purge_auth ();
  msg (M_CLIENT, "SUCCESS: Passwords were forgotten");
}

static void
man_net (struct management *man)
{
  if (man->persist.callback.show_net)
    {
      (*man->persist.callback.show_net) (man->persist.callback.arg, M_CLIENT);
    }
  else
    {
      msg (M_CLIENT, "ERROR: The 'net' command is not supported by the current daemon mode");
    }
}

static void
man_hold (struct management *man, const char *cmd)
{
  if (cmd)
    {
      if (streq (cmd, "on"))
	{
	  man->settings.hold = true;
	  msg (M_CLIENT, "SUCCESS: hold flag set to ON");
	}
      else if (streq (cmd, "off"))
	{
	  man->settings.hold = false;
	  msg (M_CLIENT, "SUCCESS: hold flag set to OFF");
	}
      else if (streq (cmd, "release"))
	{
	  man->persist.hold_release = true;
	  msg (M_CLIENT, "SUCCESS: hold release succeeded");
	}
      else
	{
	  msg (M_CLIENT, "ERROR: bad hold command parameter");
	}
    }
  else
    msg (M_CLIENT, "SUCCESS: hold=%d", (int) man->settings.hold);
}

#define MN_AT_LEAST (1<<0)

static bool
man_need (struct management *man, const char **p, const int n, unsigned int flags)
{
  int i;
  ASSERT (p[0]);
  for (i = 1; i <= n; ++i)
    {
      if (!p[i])
	{
	  msg (M_CLIENT, "ERROR: the '%s' command requires %s%d parameter%s",
	       p[0],
	       (flags & MN_AT_LEAST) ? "at least " : "",
	       n,
	       n > 1 ? "s" : "");
	  return false;
	}
    }
  return true;
}

static void
man_dispatch_command (struct management *man, struct status_output *so, const char **p, const int nparms)
{
  struct gc_arena gc = gc_new ();

  ASSERT (p[0]);
  if (streq (p[0], "exit") || streq (p[0], "quit"))
    {
      man->connection.halt = true;
      goto done;
    }
  else if (streq (p[0], "help"))
    {
      man_help ();
    }
  else if (streq (p[0], "version"))
    {
      msg (M_CLIENT, "OpenVPN Version: %s", title_string);
      msg (M_CLIENT, "Management Version: %d", MANAGEMENT_VERSION);
      msg (M_CLIENT, "END");
    }
  else if (streq (p[0], "signal"))
    {
      if (man_need (man, p, 1, 0))
	man_signal (man, p[1]);
    }
  else if (streq (p[0], "status"))
    {
      int version = 0;
      if (p[1])
	version = atoi (p[1]);
      man_status (man, version, so);
    }
  else if (streq (p[0], "kill"))
    {
      if (man_need (man, p, 1, 0))
	man_kill (man, p[1]);
    }
  else if (streq (p[0], "verb"))
    {
      if (p[1])
	{
	  const int level = atoi(p[1]);
	  if (set_debug_level (level, 0))
	    msg (M_CLIENT, "SUCCESS: verb level changed");
	  else
	    msg (M_CLIENT, "ERROR: verb level is out of range");
	}
      else
	msg (M_CLIENT, "SUCCESS: verb=%d", get_debug_level ());
    }
  else if (streq (p[0], "mute"))
    {
      if (p[1])
	{
	  const int level = atoi(p[1]);
	  if (set_mute_cutoff (level))
	    msg (M_CLIENT, "SUCCESS: mute level changed");
	  else
	    msg (M_CLIENT, "ERROR: mute level is out of range");
	}
      else
	msg (M_CLIENT, "SUCCESS: mute=%d", get_mute_cutoff ());
    }
  else if (streq (p[0], "auth-retry"))
    {
#if P2MP
      if (p[1])
	{
	  if (auth_retry_set (M_CLIENT, p[1]))
	    msg (M_CLIENT, "SUCCESS: auth-retry parameter changed");
	  else
	    msg (M_CLIENT, "ERROR: bad auth-retry parameter");
	}
      else
	msg (M_CLIENT, "SUCCESS: auth-retry=%s", auth_retry_print ());	
#else
      msg (M_CLIENT, "ERROR: auth-retry feature is unavailable");
#endif
    }
  else if (streq (p[0], "state"))
    {
      if (!p[1])
	{
	  man_state (man, "1");
	}
      else
	{
	  if (p[1])
	    man_state (man, p[1]);
	  if (p[2])
	    man_state (man, p[2]);
	}
    }
  else if (streq (p[0], "log"))
    {
      if (man_need (man, p, 1, MN_AT_LEAST))
	{
	  if (p[1])
	    man_log (man, p[1]);
	  if (p[2])
	    man_log (man, p[2]);
	}
    }
  else if (streq (p[0], "echo"))
    {
      if (man_need (man, p, 1, MN_AT_LEAST))
	{
	  if (p[1])
	    man_echo (man, p[1]);
	  if (p[2])
	    man_echo (man, p[2]);
	}
    }
  else if (streq (p[0], "username"))
    {
      if (man_need (man, p, 2, 0))
	man_query_username (man, p[1], p[2]);
    }
  else if (streq (p[0], "password"))
    {
      if (man_need (man, p, 2, 0))
	man_query_password (man, p[1], p[2]);
    }
  else if (streq (p[0], "forget-passwords"))
    {
      man_forget_passwords (man);
    }
  else if (streq (p[0], "needok"))
    {
      if (man_need (man, p, 2, 0))
	man_query_need_ok (man, p[1], p[2]);
    }
  else if (streq (p[0], "net"))
    {
      man_net (man);
    }
  else if (streq (p[0], "hold"))
    {
      man_hold (man, p[1]);
    }
  else if (streq (p[0], "bytecount"))
    {
      if (man_need (man, p, 1, 0))
	man_bytecount (man, atoi(p[1]));
    }
#if 1
  else if (streq (p[0], "test"))
    {
      if (man_need (man, p, 1, 0))
	{
	  int i;
	  const int n = atoi (p[1]);
	  for (i = 0; i < n; ++i)
	    {
	      msg (M_CLIENT, "[%d] The purpose of this command is to generate large amounts of output.", i);
	    }
	}
    }
#endif
  else
    {
      msg (M_CLIENT, "ERROR: unknown command, enter 'help' for more options");
    }

 done:
  gc_free (&gc);
}

#ifdef WIN32

static void
man_start_ne32 (struct management *man)
{
  switch (man->connection.state)
    {
    case MS_LISTEN:
      net_event_win32_start (&man->connection.ne32, FD_ACCEPT, man->connection.sd_top);
      break;
    case MS_CC_WAIT_READ:
    case MS_CC_WAIT_WRITE:
      net_event_win32_start (&man->connection.ne32, FD_READ|FD_WRITE|FD_CLOSE, man->connection.sd_cli);
      break;
    default:
      ASSERT (0);
    }  
}

static void
man_stop_ne32 (struct management *man)
{
  net_event_win32_stop (&man->connection.ne32);
}

#endif

static void
man_record_peer_info (struct management *man)
{
  struct gc_arena gc = gc_new ();
  if (man->settings.write_peer_info_file)
    {
      bool success = false;
#ifdef HAVE_GETSOCKNAME
      if (socket_defined (man->connection.sd_cli))
	{
	  struct sockaddr_in addr;
	  socklen_t addrlen = sizeof (addr);
	  int status;

	  CLEAR (addr);
	  status = getsockname (man->connection.sd_cli, (struct sockaddr *)&addr, &addrlen);
	  if (!status && addrlen == sizeof (addr))
	    {
	      const in_addr_t a = ntohl (addr.sin_addr.s_addr);
	      const int p = ntohs (addr.sin_port);
	      FILE *fp = fopen (man->settings.write_peer_info_file, "w");
	      if (fp)
		{
		  fprintf (fp, "%s\n%d\n", print_in_addr_t (a, 0, &gc), p);
		  if (!fclose (fp))
		    success = true;
		}
	    }
	}
#endif
      if (!success)
	{
	  msg (D_MANAGEMENT, "MANAGEMENT: failed to write peer info to file %s",
	       man->settings.write_peer_info_file);
	  throw_signal_soft (SIGTERM, "management-connect-failed");
	}
    }
  gc_free (&gc);
}

static void
man_connection_settings_reset (struct management *man)
{
  man->connection.state_realtime = false;
  man->connection.log_realtime = false;
  man->connection.echo_realtime = false;
  man->connection.bytecount_update_seconds = 0;
  man->connection.password_verified = false;
  man->connection.password_tries = 0;
  man->connection.halt = false;
  man->connection.state = MS_CC_WAIT_WRITE;
}

static void
man_new_connection_post (struct management *man, const char *description)
{
  struct gc_arena gc = gc_new ();

  set_nonblock (man->connection.sd_cli);
  set_cloexec (man->connection.sd_cli);

  man_connection_settings_reset (man);

#ifdef WIN32
  man_start_ne32 (man);
#endif

  msg (D_MANAGEMENT, "MANAGEMENT: %s %s",
       description,
       print_sockaddr (&man->settings.local, &gc));

  output_list_reset (man->connection.out);

  if (!man_password_needed (man))
    man_welcome (man);
  man_prompt (man);
  man_update_io_state (man);

  gc_free (&gc);
}

static void
man_accept (struct management *man)
{
  struct link_socket_actual act;

  /*
   * Accept the TCP client.
   */
  man->connection.sd_cli = socket_do_accept (man->connection.sd_top, &act, false);
  if (socket_defined (man->connection.sd_cli))
    {
      man->connection.remote = act.dest;

      if (socket_defined (man->connection.sd_top))
	{
#ifdef WIN32
	  man_stop_ne32 (man);
#endif
	}

      man_new_connection_post (man, "Client connected from");
    }
}

static void
man_listen (struct management *man)
{
  struct gc_arena gc = gc_new ();

  /*
   * Initialize state
   */
  man->connection.state = MS_LISTEN;
  man->connection.sd_cli = SOCKET_UNDEFINED;

  /*
   * Initialize listening socket
   */
  if (man->connection.sd_top == SOCKET_UNDEFINED)
    {
      man->connection.sd_top = create_socket_tcp ();

      /*
       * Bind socket
       */
      socket_bind (man->connection.sd_top, &man->settings.local, "MANAGEMENT");

      /*
       * Listen for connection
       */
      if (listen (man->connection.sd_top, 1))
	msg (M_SOCKERR, "MANAGEMENT: listen() failed");

      /*
       * Set misc socket properties
       */
      set_nonblock (man->connection.sd_top);
      set_cloexec (man->connection.sd_top);

      msg (D_MANAGEMENT, "MANAGEMENT: TCP Socket listening on %s",
	   print_sockaddr (&man->settings.local, &gc));
    }

#ifdef WIN32
  man_start_ne32 (man);
#endif
  
  gc_free (&gc);
}

static void
man_connect (struct management *man)
{
  struct gc_arena gc = gc_new ();
  int status;
  int signal_received = 0;

  /*
   * Initialize state
   */
  man->connection.state = MS_INITIAL;
  man->connection.sd_top = SOCKET_UNDEFINED;

  man->connection.sd_cli = create_socket_tcp ();

  status = openvpn_connect (man->connection.sd_cli,
			    &man->settings.local,
			    5,
			    &signal_received);

  if (signal_received)
    {
      throw_signal (signal_received);
      goto done;
    }

  if (status)
    {
      msg (D_LINK_ERRORS,
	   "MANAGEMENT: connect to %s failed: %s",
	   print_sockaddr (&man->settings.local, &gc),
	   strerror_ts (status, &gc));
      throw_signal_soft (SIGTERM, "management-connect-failed");
      goto done;
    }

  man_record_peer_info (man);
  man_new_connection_post (man, "Connected to management server at");

 done:
  gc_free (&gc);
}

static void
man_reset_client_socket (struct management *man, const bool exiting)
{
  if (socket_defined (man->connection.sd_cli))
    {
      msg (D_MANAGEMENT, "MANAGEMENT: Client disconnected");
#ifdef WIN32
      man_stop_ne32 (man);
#endif
      man_close_socket (man, man->connection.sd_cli);
      man->connection.sd_cli = SOCKET_UNDEFINED;
      command_line_reset (man->connection.in);
      output_list_reset (man->connection.out);
    }
  if (!exiting)
    {
      if (man->settings.management_forget_disconnect)
	 ssl_purge_auth ();

      if (man->settings.signal_on_disconnect) {
      	  int mysig = man_mod_signal (man, SIGUSR1);
	  if (mysig >= 0)
	    {
	      msg (D_MANAGEMENT, "MANAGEMENT: Triggering management signal");
	      throw_signal_soft (mysig, "management-disconnect");
	    }
      }

      if (man->settings.connect_as_client)
	{
	  msg (D_MANAGEMENT, "MANAGEMENT: Triggering management exit");
	  throw_signal_soft (SIGTERM, "management-exit");
	}
      else
	man_listen (man);
    }
}

static void
man_process_command (struct management *man, const char *line)
{
  struct gc_arena gc = gc_new ();
  struct status_output *so;
  int nparms;
  char *parms[MAX_PARMS+1];

  CLEAR (parms);
  so = status_open (NULL, 0, -1, &man->persist.vout, 0);

  if (man_password_needed (man))
    {
      man_check_password (man, line);
    }
  else
    {
      nparms = parse_line (line, parms, MAX_PARMS, "TCP", 0, M_CLIENT, &gc);
      if (parms[0] && streq (parms[0], "password"))
	msg (D_MANAGEMENT_DEBUG, "MANAGEMENT: CMD 'password [...]'");
      else
	msg (D_MANAGEMENT_DEBUG, "MANAGEMENT: CMD '%s'", line);

#if 0
      /* DEBUGGING -- print args */
      {
	int i;
	for (i = 0; i < nparms; ++i)
	  msg (M_INFO, "[%d] '%s'", i, parms[i]);
      }
#endif

      if (nparms > 0)
	man_dispatch_command (man, so, (const char **)parms, nparms);
    }

  CLEAR (parms);
  status_close (so);
  gc_free (&gc);
}

static bool
man_io_error (struct management *man, const char *prefix)
{
  const int err = openvpn_errno_socket ();

  if (!ignore_sys_error (err))
    {
      struct gc_arena gc = gc_new ();
      msg (D_MANAGEMENT, "MANAGEMENT: TCP %s error: %s",
	   prefix,
	   strerror_ts (err, &gc));
      gc_free (&gc);
      return true;
    }
  else
    return false;
}

static int
man_read (struct management *man)
{
  /*
   * read command line from socket
   */
  unsigned char buf[256];
  int len = 0;

  len = recv (man->connection.sd_cli, buf, sizeof (buf), MSG_NOSIGNAL);
  if (len == 0)
    {
      man_reset_client_socket (man, false);
    }
  else if (len > 0)
    {
      bool processed_command = false;

      ASSERT (len <= (int) sizeof (buf));
      command_line_add (man->connection.in, buf, len);

      /*
       * Reset output object
       */
      output_list_reset (man->connection.out);

      /*
       * process command line if complete
       */
      {
	const unsigned char *line;
	while ((line = command_line_get (man->connection.in)))
	  {
	    man_process_command (man, (char *) line);
	    if (man->connection.halt)
	      break;
	    command_line_next (man->connection.in);
	    processed_command = true;
	  }
      }

      /*
       * Reset output state to MS_CC_WAIT_(READ|WRITE)
       */
      if (man->connection.halt)
	{
	  man_reset_client_socket (man, false);
	  len = 0;
	}
      else
	{
	  if (processed_command)
	    man_prompt (man);
	  man_update_io_state (man);
	}
    }
  else /* len < 0 */
    {
      if (man_io_error (man, "recv"))
	man_reset_client_socket (man, false);
    }
  return len;
}

static int
man_write (struct management *man)
{
  const int max_send = 256;
  int sent = 0;

  const struct buffer *buf = output_list_peek (man->connection.out);
  if (buf && BLEN (buf))
    {
      const int len = min_int (max_send, BLEN (buf));
      sent = send (man->connection.sd_cli, BPTR (buf), len, MSG_NOSIGNAL);
      if (sent >= 0)
	{
	  output_list_advance (man->connection.out, sent);
	}
      else if (sent < 0)
	{
	  if (man_io_error (man, "send"))
	    man_reset_client_socket (man, false);
	}
    }

  /*
   * Reset output state to MS_CC_WAIT_(READ|WRITE)
   */
  man_update_io_state (man);

  return sent;
}

static void
man_connection_clear (struct man_connection *mc)
{
  CLEAR (*mc);

  /* set initial state */
  mc->state = MS_INITIAL;

  /* clear socket descriptors */
  mc->sd_top = SOCKET_UNDEFINED;
  mc->sd_cli = SOCKET_UNDEFINED;
}

static void
man_persist_init (struct management *man,
		  const int log_history_cache,
		  const int echo_buffer_size,
		  const int state_buffer_size)
{
  struct man_persist *mp = &man->persist;
  if (!mp->defined)
    {
      CLEAR (*mp);

      /* initialize log history store */
      mp->log = log_history_init (log_history_cache);  

      /*
       * Initialize virtual output object, so that functions
       * which write to a virtual_output object can be redirected
       * here to the management object.
       */
      mp->vout.func = virtual_output_callback_func;
      mp->vout.arg = man;
      mp->vout.flags_default = M_CLIENT;
      msg_set_virtual_output (&mp->vout);

      /*
       * Initialize --echo list
       */
      man->persist.echo = log_history_init (echo_buffer_size);

      /*
       * Initialize --state list
       */
      man->persist.state = log_history_init (state_buffer_size);

      mp->defined = true;
    }
}

static void
man_persist_close (struct man_persist *mp)
{
  if (mp->log)
    {
      msg_set_virtual_output (NULL);
      log_history_close (mp->log);
    }

  if (mp->echo)
    log_history_close (mp->echo);

  if (mp->state)
    log_history_close (mp->state);

  CLEAR (*mp);
}
      
static void
man_settings_init (struct man_settings *ms,
		   const char *addr,
		   const int port,
		   const char *pass_file,
		   const bool server,
		   const bool query_passwords,
		   const int log_history_cache,
		   const int echo_buffer_size,
		   const int state_buffer_size,
		   const bool hold,
		   const bool signal_on_disconnect,
		   const bool management_forget_disconnect,
		   const bool connect_as_client,
		   const char *write_peer_info_file,
		   const int remap_sigusr1)
{
  if (!ms->defined)
    {
      CLEAR (*ms);

      /*
       * Are we a server?  If so, it will influence
       * the way we handle state transitions.
       */
      ms->server = server;

      /*
       * Get username/password
       */
      if (pass_file)
	get_user_pass (&ms->up, pass_file, "Management", GET_USER_PASS_PASSWORD_ONLY);

      /*
       * Should OpenVPN query the management layer for
       * passwords?
       */
      ms->up_query_passwords = query_passwords;

      /*
       * Should OpenVPN hibernate on startup?
       */
      ms->hold = hold;

      /*
       * Should OpenVPN be signaled if management
       * disconnects?
       */
      ms->signal_on_disconnect = signal_on_disconnect;

      /*
       * Should OpenVPN forget passwords when managmenet
       * session disconnects?
       */
      ms->management_forget_disconnect = management_forget_disconnect;

      /*
       * Should OpenVPN connect to management interface as a client
       * rather than a server?
       */
      ms->connect_as_client = connect_as_client;
      ms->write_peer_info_file = string_alloc (write_peer_info_file, NULL);

      /*
       * Initialize socket address
       */
      ms->local.sa.sin_family = AF_INET;
      ms->local.sa.sin_addr.s_addr = 0;
      ms->local.sa.sin_port = htons (port);

      /*
       * Run management over tunnel, or
       * separate channel?
       */
      if (streq (addr, "tunnel") && !connect_as_client)
	{
	  ms->management_over_tunnel = true;
	}
      else
	{
	  ms->local.sa.sin_addr.s_addr = getaddr
	    (GETADDR_RESOLVE|GETADDR_WARN_ON_SIGNAL|GETADDR_FATAL, addr, 0, NULL, NULL);
	}
      
      /*
       * Log history and echo buffer may need to be resized
       */
      ms->log_history_cache = log_history_cache;
      ms->echo_buffer_size = echo_buffer_size;
      ms->state_buffer_size = state_buffer_size;

      /*
       * Set remap sigusr1 flags
       */
      if (remap_sigusr1 == SIGHUP)
	ms->mansig |= MANSIG_MAP_USR1_TO_HUP;
      else if (remap_sigusr1 == SIGTERM)
	ms->mansig |= MANSIG_MAP_USR1_TO_TERM;

      ms->defined = true;
    }
}

static void
man_settings_close (struct man_settings *ms)
{
  free (ms->write_peer_info_file);
  CLEAR (*ms);
}


static void
man_connection_init (struct management *man)
{
  if (man->connection.state == MS_INITIAL)
    {
#ifdef WIN32
      /*
       * This object is a sort of TCP/IP helper
       * for Windows.
       */
      net_event_win32_init (&man->connection.ne32);
#endif

      /*
       * Allocate helper objects for command line input and
       * command output from/to the socket.
       */
      man->connection.in = command_line_new (256);
      man->connection.out = output_list_new (0);

      /*
       * Initialize event set for standalone usage, when we are
       * running outside of the primary event loop.
       */
      {
	int maxevents = 1;
	man->connection.es = event_set_init (&maxevents, EVENT_METHOD_FAST);
      }

      /*
       * Listen/connect socket
       */
      if (man->settings.connect_as_client)
	man_connect (man);
      else
	man_listen (man);
    }
}

static void
man_connection_close (struct management *man)
{
  struct man_connection *mc = &man->connection;

  if (mc->es)
    event_free (mc->es);
#ifdef WIN32
  net_event_win32_close (&mc->ne32);
#endif
  if (socket_defined (mc->sd_top))
    man_close_socket (man, mc->sd_top);
  if (socket_defined (mc->sd_cli))
    man_close_socket (man, mc->sd_cli);
  if (mc->in)
    command_line_free (mc->in);
  if (mc->out)
    output_list_free (mc->out);
  man_connection_clear (mc);
}

struct management *
management_init (void)
{
  struct management *man;
  ALLOC_OBJ_CLEAR (man, struct management);

  man_persist_init (man,
		    MANAGEMENT_LOG_HISTORY_INITIAL_SIZE,
		    MANAGEMENT_ECHO_BUFFER_SIZE,
		    MANAGEMENT_STATE_BUFFER_SIZE);

  man_connection_clear (&man->connection);

  return man;
}

bool
management_open (struct management *man,
		 const char *addr,
		 const int port,
		 const char *pass_file,
		 const bool server,
		 const bool query_passwords,
		 const int log_history_cache,
		 const int echo_buffer_size,
		 const int state_buffer_size,
		 const bool hold,
		 const bool signal_on_disconnect,
		 const bool management_forget_disconnect,
		 const bool connect_as_client,
		 const char *write_peer_info_file,
		 const int remap_sigusr1)
{
  bool ret = false;

  /*
   * Save the settings only if they have not
   * been saved before.
   */
  man_settings_init (&man->settings,
		     addr,
		     port,
		     pass_file,
		     server,
		     query_passwords,
		     log_history_cache,
		     echo_buffer_size,
		     state_buffer_size,
		     hold,
		     signal_on_disconnect,
		     management_forget_disconnect,
		     connect_as_client,
		     write_peer_info_file,
		     remap_sigusr1);

  /*
   * The log is initially sized to MANAGEMENT_LOG_HISTORY_INITIAL_SIZE,
   * but may be changed here.  Ditto for echo and state buffers.
   */
  log_history_resize (man->persist.log, man->settings.log_history_cache);
  log_history_resize (man->persist.echo, man->settings.echo_buffer_size);
  log_history_resize (man->persist.state, man->settings.state_buffer_size);

  /*
   * If connection object is uninitialized and we are not doing
   * over-the-tunnel management, then open (listening) connection.
   */
  if (man->connection.state == MS_INITIAL)
    {
      if (!man->settings.management_over_tunnel)
	{
	  man_connection_init (man);
	  ret = true;
	}
    }

  return ret;
}

void
management_close (struct management *man)
{
  man_connection_close (man);
  man_settings_close (&man->settings);
  man_persist_close (&man->persist);
  free (man);
}

void
management_set_callback (struct management *man,
			 const struct management_callback *cb)
{
  man->persist.standalone_disabled = true;
  man->persist.callback = *cb;
}

void
management_clear_callback (struct management *man)
{
  man->persist.standalone_disabled = false;
  man->persist.hold_release = false;
  CLEAR (man->persist.callback);
  man_output_list_push (man, NULL); /* flush output queue */
}

void
management_set_state (struct management *man,
		      const int state,
		      const char *detail,
		      const in_addr_t tun_local_ip,
		      const in_addr_t tun_remote_ip)
{
  if (man->persist.state && (!man->settings.server || state < OPENVPN_STATE_CLIENT_BASE))
    {
      struct gc_arena gc = gc_new ();
      struct log_entry e;
      const char *out = NULL;

      update_time ();
      CLEAR (e);
      e.timestamp = now;
      e.u.state = state;
      e.string = detail;
      e.local_ip = tun_local_ip;
      e.remote_ip = tun_remote_ip;
      
      log_history_add (man->persist.state, &e);

      if (man->connection.state_realtime)
	out = log_entry_print (&e, LOG_PRINT_STATE_PREFIX
			       |   LOG_PRINT_INT_DATE
                               |   LOG_PRINT_STATE
			       |   LOG_PRINT_LOCAL_IP
			       |   LOG_PRINT_REMOTE_IP
                               |   LOG_PRINT_CRLF
			       |   LOG_ECHO_TO_LOG, &gc);

      if (out)
	man_output_list_push (man, out);

      gc_free (&gc);
    }
}

void
management_echo (struct management *man, const char *string, const bool pull)
{
  if (man->persist.echo)
    {
      struct gc_arena gc = gc_new ();
      struct log_entry e;
      const char *out = NULL;

      update_time ();
      CLEAR (e);
      e.timestamp = now;
      e.string = string;
      e.u.intval = BOOL_CAST (pull);

      log_history_add (man->persist.echo, &e);

      if (man->connection.echo_realtime)
	out = log_entry_print (&e, LOG_PRINT_INT_DATE|LOG_PRINT_ECHO_PREFIX|LOG_PRINT_CRLF|MANAGEMENT_ECHO_FLAGS, &gc);

      if (out)
	man_output_list_push (man, out);

      gc_free (&gc);
    }
}

void
management_post_tunnel_open (struct management *man, const in_addr_t tun_local_ip)
{
  /*
   * If we are running management over the tunnel,
   * this is the place to initialize the connection.
   */
  if (man->settings.management_over_tunnel
      && man->connection.state == MS_INITIAL)
    {
      /* listen on our local TUN/TAP IP address */
      man->settings.local.sa.sin_addr.s_addr = htonl (tun_local_ip);
      man_connection_init (man);
    }

}

void
management_pre_tunnel_close (struct management *man)
{
  if (man->settings.management_over_tunnel)
    man_connection_close (man);
}

void
management_auth_failure (struct management *man, const char *type)
{
  msg (M_CLIENT, ">PASSWORD:Verification Failed: '%s'", type);
}

static inline bool
man_persist_state (unsigned int *persistent, const int n)
{
  if (persistent)
    {
      if (*persistent == (unsigned int)n)
	return false;
      *persistent = n;
    }
  return true;
}

#ifdef WIN32

void
management_socket_set (struct management *man,
		       struct event_set *es,
		       void *arg,
		       unsigned int *persistent)
{
  if (man->connection.state != MS_INITIAL)
    {
      event_t ev = net_event_win32_get_event (&man->connection.ne32);
      net_event_win32_reset_write (&man->connection.ne32);

      switch (man->connection.state)
	{
	case MS_LISTEN:
	  if (man_persist_state (persistent, 1))
	    event_ctl (es, ev, EVENT_READ, arg);
	  break;
	case MS_CC_WAIT_READ:
	  if (man_persist_state (persistent, 2))
	    event_ctl (es, ev, EVENT_READ, arg);
	  break;
	case MS_CC_WAIT_WRITE:
	  if (man_persist_state (persistent, 3))
	    event_ctl (es, ev, EVENT_READ|EVENT_WRITE, arg);
	  break;
	default:
	  ASSERT (0);
	}
    }
}

void
management_io (struct management *man)
{
  if (man->connection.state != MS_INITIAL)
    {
      long net_events;
      net_event_win32_reset (&man->connection.ne32);
      net_events = net_event_win32_get_event_mask (&man->connection.ne32);

      if (net_events & FD_CLOSE)
	{
	  man_reset_client_socket (man, false);
	}
      else
	{
	  if (man->connection.state == MS_LISTEN)
	    {
	      if (net_events & FD_ACCEPT)
		{
		  man_accept (man);
		  net_event_win32_clear_selected_events (&man->connection.ne32, FD_ACCEPT);
		}
	    }
	  else if (man->connection.state == MS_CC_WAIT_READ)
	    {
	      if (net_events & FD_READ)
		{
		  man_read (man);
		  net_event_win32_clear_selected_events (&man->connection.ne32, FD_READ);
		}
	    }

	  if (man->connection.state == MS_CC_WAIT_WRITE)
	    {
	      if (net_events & FD_WRITE)
		{
		  int status;
		  /* dmsg (M_INFO, "FD_WRITE set"); */
		  status = man_write (man);
		  if (status < 0 && WSAGetLastError() == WSAEWOULDBLOCK)
		    {
		      /* dmsg (M_INFO, "FD_WRITE cleared"); */
		      net_event_win32_clear_selected_events (&man->connection.ne32, FD_WRITE);
		    }
		}
	    }
	}
    }
}

#else

void
management_socket_set (struct management *man,
		       struct event_set *es,
		       void *arg,
		       unsigned int *persistent)
{
  switch (man->connection.state)
    {
    case MS_LISTEN:
      if (man_persist_state (persistent, 1))
	event_ctl (es, man->connection.sd_top, EVENT_READ, arg);
      break;
    case MS_CC_WAIT_READ:
      if (man_persist_state (persistent, 2))
	event_ctl (es, man->connection.sd_cli, EVENT_READ, arg);
      break;
    case MS_CC_WAIT_WRITE:
      if (man_persist_state (persistent, 3))
	event_ctl (es, man->connection.sd_cli, EVENT_WRITE, arg);
      break;
    case MS_INITIAL:
      break;
    default:
      ASSERT (0);
    }
}

void
management_io (struct management *man)
{
  switch (man->connection.state)
    {
    case MS_LISTEN:
      man_accept (man);
      break;
    case MS_CC_WAIT_READ:
      man_read (man);
      break;
    case MS_CC_WAIT_WRITE:
      man_write (man);
      break;
    case MS_INITIAL:
      break;
    default:
      ASSERT (0);
    }
}

#endif

static inline bool
man_standalone_ok (const struct management *man)
{
  return !man->settings.management_over_tunnel && man->connection.state != MS_INITIAL;
}

static bool
man_check_for_signals (volatile int *signal_received)
{
  if (signal_received)
    {
      get_signal (signal_received);
      if (*signal_received)
	return true;
    }
  return false;
}

/*
 * Wait for socket I/O when outside primary event loop
 */
static int
man_block (struct management *man, volatile int *signal_received, const time_t expire)
{
  struct timeval tv;
  struct event_set_return esr;
  int status = -1;
  
  if (man_standalone_ok (man))
    {
      do
	{
	  event_reset (man->connection.es);
	  management_socket_set (man, man->connection.es, NULL, NULL);
	  tv.tv_usec = 0;
	  tv.tv_sec = 1;
	  if (man_check_for_signals (signal_received))
	    {
	      status = -1;
	      break;
	    }
	  status = event_wait (man->connection.es, &tv, &esr, 1);
	  update_time ();
	  if (man_check_for_signals (signal_received))
	    {
	      status = -1;
	      break;
	    }
	  /* set SIGINT signal if expiration time exceeded */
	  if (expire && now >= expire)
	    {
	      status = 0;
	      if (signal_received)
		*signal_received = SIGINT;
	      break;
	    }
	} while (status != 1);
    }
  return status;
}

/*
 * Perform management socket output outside primary event loop
 */
static void
man_output_standalone (struct management *man, volatile int *signal_received)
{
  if (man_standalone_ok (man))
    {
      while (man->connection.state == MS_CC_WAIT_WRITE)
	{
	  management_io (man);
	  if (man->connection.state == MS_CC_WAIT_WRITE)
	    man_block (man, signal_received, 0);
	  if (signal_received && *signal_received)
	    break;
	}
    }
}

/*
 * Process management event loop outside primary event loop
 */
static int
man_standalone_event_loop (struct management *man, volatile int *signal_received, const time_t expire)
{
  int status;
  ASSERT (man_standalone_ok (man));
  status = man_block (man, signal_received, expire);
  if (status > 0)
    management_io (man);
  return status;
}

#define MWCC_PASSWORD_WAIT (1<<0)
#define MWCC_HOLD_WAIT     (1<<1)

/*
 * Block until client connects
 */
static void
man_wait_for_client_connection (struct management *man,
				volatile int *signal_received,
				const time_t expire,
				unsigned int flags)
{
  ASSERT (man_standalone_ok (man));
  if (man->connection.state == MS_LISTEN)
    {
      if (flags & MWCC_PASSWORD_WAIT)
	msg (D_MANAGEMENT, "Need password(s) from management interface, waiting...");
      if (flags & MWCC_HOLD_WAIT)
	msg (D_MANAGEMENT, "Need hold release from management interface, waiting...");
      do {
	man_standalone_event_loop (man, signal_received, expire);
	if (signal_received && *signal_received)
	  break;
      } while (man->connection.state == MS_LISTEN || man_password_needed (man));
    }
}

/*
 * Process the management event loop for sec seconds
 */
void
management_event_loop_n_seconds (struct management *man, int sec)
{
  if (man_standalone_ok (man))
    {
      volatile int signal_received = 0;
      const bool standalone_disabled_save = man->persist.standalone_disabled;
      time_t expire;

      man->persist.standalone_disabled = false; /* This is so M_CLIENT messages will be correctly passed through msg() */

      /* set expire time */