summaryrefslogtreecommitdiffstats
path: root/source4/smb_server/tcon.c
diff options
context:
space:
mode:
authorStefan Metzmacher <metze@samba.org>2006-03-10 14:31:17 +0000
committerGerald (Jerry) Carter <jerry@samba.org>2007-10-10 13:56:55 -0500
commit86497db6113c4ec3210d671c3fcf957d1026098c (patch)
treeea7aaa040264907802688b8154873603f4f4635c /source4/smb_server/tcon.c
parentb86c1b744b48a2b664c9075335eb48098e4462fd (diff)
downloadsamba-86497db6113c4ec3210d671c3fcf957d1026098c.tar.gz
samba-86497db6113c4ec3210d671c3fcf957d1026098c.tar.xz
samba-86497db6113c4ec3210d671c3fcf957d1026098c.zip
r14157: - pass a struct ntvfs_request to the ntvfs layer
(for now we just do #define ntvfs_request smbsrv_request, but it's the first step...) - rename ntvfs_openfile() -> ntvfs_open() - fix the talloc hierachie in some places in the ntvfs_map_*() code metze (This used to be commit ed9ed1f48f602354810937c0b0de850b44322191)
Diffstat (limited to 'source4/smb_server/tcon.c')
-rw-r--r--source4/smb_server/tcon.c2
1 files changed, 1 insertions, 1 deletions
diff --git a/source4/smb_server/tcon.c b/source4/smb_server/tcon.c
index e0def0ab3f..90fe20a4c8 100644
--- a/source4/smb_server/tcon.c
+++ b/source4/smb_server/tcon.c
@@ -102,7 +102,7 @@ static int smbsrv_tcon_destructor(void *ptr)
/* tell the ntvfs backend that we are disconnecting */
if (tcon->ntvfs_ctx) {
- ntvfs_disconnect(tcon);
+ ntvfs_disconnect(tcon->ntvfs_ctx);
}
if (tcon->smb2.session) {
='n172' href='#n172'>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 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 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590
/*
   Unix SMB/CIFS implementation.
   Infrastructure for async ldap client requests
   Copyright (C) Volker Lendecke 2009

   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/>.
*/

#include "includes.h"
#include "tldap.h"
#include "../lib/util/asn1.h"
#include "../lib/tsocket/tsocket.h"
#include "../lib/util/tevent_unix.h"

static int tldap_simple_recv(struct tevent_req *req);

bool tevent_req_is_ldap_error(struct tevent_req *req, int *perr)
{
	enum tevent_req_state state;
	uint64_t err;

	if (!tevent_req_is_error(req, &state, &err)) {
		return false;
	}
	switch (state) {
	case TEVENT_REQ_TIMED_OUT:
		*perr = TLDAP_TIMEOUT;
		break;
	case TEVENT_REQ_NO_MEMORY:
		*perr = TLDAP_NO_MEMORY;
		break;
	case TEVENT_REQ_USER_ERROR:
		*perr = err;
		break;
	default:
		*perr = TLDAP_OPERATIONS_ERROR;
		break;
	}
	return true;
}

struct tldap_ctx_attribute {
	char *name;
	void *ptr;
};

struct tldap_context {
	int ld_version;
	int ld_deref;
	int ld_sizelimit;
	int ld_timelimit;
	struct tstream_context *conn;
	bool server_down;
	int msgid;
	struct tevent_queue *outgoing;
	struct tevent_req **pending;

	/* For the sync wrappers we need something like get_last_error... */
	struct tldap_message *last_msg;

	/* debug */
	void (*log_fn)(void *context, enum tldap_debug_level level,
		       const char *fmt, va_list ap);
	void *log_private;

	struct tldap_ctx_attribute *ctx_attrs;
};

struct tldap_message {
	struct asn1_data *data;
	uint8_t *inbuf;
	int type;
	int id;

	/* RESULT_ENTRY */
	char *dn;
	struct tldap_attribute *attribs;

	/* Error data sent by the server */
	int lderr;
	char *res_matcheddn;
	char *res_diagnosticmessage;
	char *res_referral;
	struct tldap_control *res_sctrls;

	/* Controls sent by the server */
	struct tldap_control *ctrls;
};

void tldap_set_debug(struct tldap_context *ld,
		     void (*log_fn)(void *log_private,
				    enum tldap_debug_level level,
				    const char *fmt,
				    va_list ap) PRINTF_ATTRIBUTE(3,0),
		     void *log_private)
{
	ld->log_fn = log_fn;
	ld->log_private = log_private;
}

static void tldap_debug(struct tldap_context *ld,
			 enum tldap_debug_level level,
			 const char *fmt, ...)
{
	va_list ap;
	if (!ld) {
		return;
	}
	if (ld->log_fn == NULL) {
		return;
	}
	va_start(ap, fmt);
	ld->log_fn(ld->log_private, level, fmt, ap);
	va_end(ap);
}

static int tldap_next_msgid(struct tldap_context *ld)
{
	int result;

	result = ld->msgid++;
	if (ld->msgid == 2147483647) {
		ld->msgid = 1;
	}
	return result;
}

struct tldap_context *tldap_context_create(TALLOC_CTX *mem_ctx, int fd)
{
	struct tldap_context *ctx;
	int ret;

	ctx = talloc_zero(mem_ctx, struct tldap_context);
	if (ctx == NULL) {
		return NULL;
	}
	ret = tstream_bsd_existing_socket(ctx, fd, &ctx->conn);
	if (ret == -1) {
		TALLOC_FREE(ctx);
		return NULL;
	}
	ctx->msgid = 1;
	ctx->ld_version = 3;
	ctx->outgoing = tevent_queue_create(ctx, "tldap_outgoing");
	if (ctx->outgoing == NULL) {
		TALLOC_FREE(ctx);
		return NULL;
	}
	return ctx;
}

bool tldap_connection_ok(struct tldap_context *ld)
{
	if (ld == NULL) {
		return false;
	}
	return !ld->server_down;
}

static struct tldap_ctx_attribute *tldap_context_findattr(
	struct tldap_context *ld, const char *name)
{
	int i, num_attrs;

	num_attrs = talloc_array_length(ld->ctx_attrs);

	for (i=0; i<num_attrs; i++) {
		if (strcmp(ld->ctx_attrs[i].name, name) == 0) {
			return &ld->ctx_attrs[i];
		}
	}
	return NULL;
}

bool tldap_context_setattr(struct tldap_context *ld,
			   const char *name, const void *_pptr)
{
	struct tldap_ctx_attribute *tmp, *attr;
	char *tmpname;
	int num_attrs;
	void **pptr = (void **)discard_const_p(void,_pptr);

	attr = tldap_context_findattr(ld, name);
	if (attr != NULL) {
		/*
		 * We don't actually delete attrs, we don't expect tons of
		 * attributes being shuffled around.
		 */
		TALLOC_FREE(attr->ptr);
		if (*pptr != NULL) {
			attr->ptr = talloc_move(ld->ctx_attrs, pptr);
			*pptr = NULL;
		}
		return true;
	}

	tmpname = talloc_strdup(ld, name);
	if (tmpname == NULL) {
		return false;
	}

	num_attrs = talloc_array_length(ld->ctx_attrs);

	tmp = talloc_realloc(ld, ld->ctx_attrs, struct tldap_ctx_attribute,
			     num_attrs+1);
	if (tmp == NULL) {
		TALLOC_FREE(tmpname);
		return false;
	}
	tmp[num_attrs].name = talloc_move(tmp, &tmpname);
	if (*pptr != NULL) {
		tmp[num_attrs].ptr = talloc_move(tmp, pptr);
	} else {
		tmp[num_attrs].ptr = NULL;
	}
	*pptr = NULL;
	ld->ctx_attrs = tmp;
	return true;
}

void *tldap_context_getattr(struct tldap_context *ld, const char *name)
{
	struct tldap_ctx_attribute *attr = tldap_context_findattr(ld, name);

	if (attr == NULL) {
		return NULL;
	}
	return attr->ptr;
}

struct read_ldap_state {
	uint8_t *buf;
	bool done;
};

static ssize_t read_ldap_more(uint8_t *buf, size_t buflen, void *private_data);
static void read_ldap_done(struct tevent_req *subreq);

static struct tevent_req *read_ldap_send(TALLOC_CTX *mem_ctx,
					 struct tevent_context *ev,
					 struct tstream_context *conn)
{
	struct tevent_req *req, *subreq;
	struct read_ldap_state *state;

	req = tevent_req_create(mem_ctx, &state, struct read_ldap_state);
	if (req == NULL) {
		return NULL;
	}
	state->done = false;

	subreq = tstream_read_packet_send(state, ev, conn, 2, read_ldap_more,
					  state);
	if (tevent_req_nomem(subreq, req)) {
		return tevent_req_post(req, ev);
	}
	tevent_req_set_callback(subreq, read_ldap_done, req);
	return req;
}

static ssize_t read_ldap_more(uint8_t *buf, size_t buflen, void *private_data)
{
	struct read_ldap_state *state = talloc_get_type_abort(
		private_data, struct read_ldap_state);
	size_t len;
	int i, lensize;

	if (state->done) {
		/* We've been here, we're done */
		return 0;
	}

	/*
	 * From ldap.h: LDAP_TAG_MESSAGE is 0x30
	 */
	if (buf[0] != 0x30) {
		return -1;
	}

	len = buf[1];
	if ((len & 0x80) == 0) {
		state->done = true;
		return len;
	}

	lensize = (len & 0x7f);
	len = 0;

	if (buflen == 2) {
		/* Please get us the full length */
		return lensize;
	}
	if (buflen > 2 + lensize) {
		state->done = true;
		return 0;
	}
	if (buflen != 2 + lensize) {
		return -1;
	}

	for (i=0; i<lensize; i++) {
		len = (len << 8) | buf[2+i];
	}
	return len;
}

static void read_ldap_done(struct tevent_req *subreq)
{
	struct tevent_req *req = tevent_req_callback_data(
		subreq, struct tevent_req);
	struct read_ldap_state *state = tevent_req_data(
		req, struct read_ldap_state);
	ssize_t nread;
	int err;

	nread = tstream_read_packet_recv(subreq, state, &state->buf, &err);
	TALLOC_FREE(subreq);
	if (nread == -1) {
		tevent_req_error(req, err);
		return;
	}
	tevent_req_done(req);
}

static ssize_t read_ldap_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
			      uint8_t **pbuf, int *perrno)
{
	struct read_ldap_state *state = tevent_req_data(
		req, struct read_ldap_state);

	if (tevent_req_is_unix_error(req, perrno)) {
		return -1;
	}
	*pbuf = talloc_move(mem_ctx, &state->buf);
	return talloc_get_size(*pbuf);
}

struct tldap_msg_state {
	struct tldap_context *ld;
	struct tevent_context *ev;
	int id;
	struct iovec iov;

	struct asn1_data *data;
	uint8_t *inbuf;
};

static void tldap_push_controls(struct asn1_data *data,
				struct tldap_control *sctrls,
				int num_sctrls)
{
	int i;

	if ((sctrls == NULL) || (num_sctrls == 0)) {
		return;
	}

	asn1_push_tag(data, ASN1_CONTEXT(0));

	for (i=0; i<num_sctrls; i++) {
		struct tldap_control *c = &sctrls[i];
		asn1_push_tag(data, ASN1_SEQUENCE(0));
		asn1_write_OctetString(data, c->oid, strlen(c->oid));
		if (c->critical) {
			asn1_write_BOOLEAN(data, true);
		}
		if (c->value.data != NULL) {
			asn1_write_OctetString(data, c->value.data,
					       c->value.length);
		}
		asn1_pop_tag(data); /* ASN1_SEQUENCE(0) */
	}

	asn1_pop_tag(data); /* ASN1_CONTEXT(0) */
}

static void tldap_msg_sent(struct tevent_req *subreq);
static void tldap_msg_received(struct tevent_req *subreq);

static struct tevent_req *tldap_msg_send(TALLOC_CTX *mem_ctx,
					 struct tevent_context *ev,
					 struct tldap_context *ld,
					 int id, struct asn1_data *data,
					 struct tldap_control *sctrls,
					 int num_sctrls)
{
	struct tevent_req *req, *subreq;
	struct tldap_msg_state *state;
	DATA_BLOB blob;

	tldap_debug(ld, TLDAP_DEBUG_TRACE, "tldap_msg_send: sending msg %d\n",
		    id);

	req = tevent_req_create(mem_ctx, &state, struct tldap_msg_state);
	if (req == NULL) {
		return NULL;
	}
	state->ld = ld;
	state->ev = ev;
	state->id = id;

	if (state->ld->server_down) {
		tevent_req_error(req, TLDAP_SERVER_DOWN);
		return tevent_req_post(req, ev);
	}

	tldap_push_controls(data, sctrls, num_sctrls);

	asn1_pop_tag(data);

	if (!asn1_blob(data, &blob)) {
		tevent_req_error(req, TLDAP_ENCODING_ERROR);
		return tevent_req_post(req, ev);
	}

	state->iov.iov_base = (void *)blob.data;
	state->iov.iov_len = blob.length;

	subreq = tstream_writev_queue_send(state, ev, ld->conn, ld->outgoing,
					   &state->iov, 1);
	if (tevent_req_nomem(subreq, req)) {
		return tevent_req_post(req, ev);
	}
	tevent_req_set_callback(subreq, tldap_msg_sent, req);
	return req;
}

static void tldap_msg_unset_pending(struct tevent_req *req)
{
	struct tldap_msg_state *state = tevent_req_data(
		req, struct tldap_msg_state);
	struct tldap_context *ld = state->ld;
	int num_pending = talloc_array_length(ld->pending);
	int i;

	if (num_pending == 1) {
		TALLOC_FREE(ld->pending);
		return;
	}

	for (i=0; i<num_pending; i++) {
		if (req == ld->pending[i]) {
			break;
		}
	}
	if (i == num_pending) {
		/*
		 * Something's seriously broken. Just returning here is the
		 * right thing nevertheless, the point of this routine is to
		 * remove ourselves from cli->pending.
		 */
		return;
	}

	/*
	 * Remove ourselves from the cli->pending array
	 */
	if (num_pending > 1) {
		ld->pending[i] = ld->pending[num_pending-1];
	}

	/*
	 * No NULL check here, we're shrinking by sizeof(void *), and
	 * talloc_realloc just adjusts the size for this.
	 */
	ld->pending = talloc_realloc(NULL, ld->pending, struct tevent_req *,
				     num_pending - 1);
	return;
}

static int tldap_msg_destructor(struct tevent_req *req)
{
	tldap_msg_unset_pending(req);
	return 0;
}

static bool tldap_msg_set_pending(struct tevent_req *req)
{
	struct tldap_msg_state *state = tevent_req_data(
		req, struct tldap_msg_state);
	struct tldap_context *ld;
	struct tevent_req **pending;
	int num_pending;
	struct tevent_req *subreq;

	ld = state->ld;
	num_pending = talloc_array_length(ld->pending);

	pending = talloc_realloc(ld, ld->pending, struct tevent_req *,
				 num_pending+1);
	if (pending == NULL) {
		return false;
	}
	pending[num_pending] = req;
	ld->pending = pending;
	talloc_set_destructor(req, tldap_msg_destructor);

	if (num_pending > 0) {
		return true;
	}

	/*
	 * We're the first one, add the read_ldap request that waits for the
	 * answer from the server
	 */
	subreq = read_ldap_send(ld->pending, state->ev, ld->conn);
	if (subreq == NULL) {
		tldap_msg_unset_pending(req);
		return false;
	}
	tevent_req_set_callback(subreq, tldap_msg_received, ld);
	return true;
}

static void tldap_msg_sent(struct tevent_req *subreq)
{
	struct tevent_req *req = tevent_req_callback_data(
		subreq, struct tevent_req);
	struct tldap_msg_state *state = tevent_req_data(
		req, struct tldap_msg_state);
	ssize_t nwritten;
	int err;

	nwritten = tstream_writev_queue_recv(subreq, &err);
	TALLOC_FREE(subreq);
	if (nwritten == -1) {
		state->ld->server_down = true;
		tevent_req_error(req, TLDAP_SERVER_DOWN);
		return;
	}

	if (!tldap_msg_set_pending(req)) {
		tevent_req_oom(req);
		return;
	}
}

static int tldap_msg_msgid(struct tevent_req *req)
{
	struct tldap_msg_state *state = tevent_req_data(
		req, struct tldap_msg_state);

	return state->id;
}

static void tldap_msg_received(struct tevent_req *subreq)
{
	struct tldap_context *ld = tevent_req_callback_data(
		subreq, struct tldap_context);
	struct tevent_req *req;
	struct tldap_msg_state *state;
	struct asn1_data *data;
	uint8_t *inbuf;
	ssize_t received;
	size_t num_pending;
	int i, err, status;
	int id;
	uint8_t type;
	bool ok;

	received = read_ldap_recv(subreq, talloc_tos(), &inbuf, &err);
	TALLOC_FREE(subreq);
	if (received == -1) {
		status = TLDAP_SERVER_DOWN;
		goto fail;
	}

	data = asn1_init(talloc_tos());
	if (data == NULL) {
		status = TLDAP_NO_MEMORY;
		goto fail;
	}
	asn1_load_nocopy(data, inbuf, received);

	ok = true;
	ok &= asn1_start_tag(data, ASN1_SEQUENCE(0));
	ok &= asn1_read_Integer(data, &id);
	ok &= asn1_peek_uint8(data, &type);

	if (!ok) {
		status = TLDAP_PROTOCOL_ERROR;
		goto fail;
	}

	tldap_debug(ld, TLDAP_DEBUG_TRACE, "tldap_msg_received: got msg %d "
		    "type %d\n", id, (int)type);

	num_pending = talloc_array_length(ld->pending);

	for (i=0; i<num_pending; i++) {
		if (id == tldap_msg_msgid(ld->pending[i])) {
			break;
		}
	}
	if (i == num_pending) {
		/* Dump unexpected reply */
		tldap_debug(ld, TLDAP_DEBUG_WARNING, "tldap_msg_received: "
			    "No request pending for msg %d\n", id);
		TALLOC_FREE(data);
		TALLOC_FREE(inbuf);
		goto done;
	}

	req = ld->pending[i];
	state = tevent_req_data(req, struct tldap_msg_state);

	state->inbuf = talloc_move(state, &inbuf);
	state->data = talloc_move(state, &data);

	talloc_set_destructor(req, NULL);
	tldap_msg_unset_pending(req);
	num_pending = talloc_array_length(ld->pending);

	tevent_req_done(req);

 done:
	if (num_pending == 0) {
		return;
	}
	if (talloc_array_length(ld->pending) > num_pending) {
		/*
		 * The callback functions called from tevent_req_done() above
		 * have put something on the pending queue. We don't have to
		 * trigger the read_ldap_send(), tldap_msg_set_pending() has
		 * done it for us already.
		 */
		return;
	}

	state = tevent_req_data(ld->pending[0],	struct tldap_msg_state);
	subreq = read_ldap_send(ld->pending, state->ev, ld->conn);
	if (subreq == NULL) {
		status = TLDAP_NO_MEMORY;
		goto fail;
	}
	tevent_req_set_callback(subreq, tldap_msg_received, ld);
	return;

 fail:
	while (talloc_array_length(ld->pending) > 0) {
		req = ld->pending[0];
		talloc_set_destructor(req, NULL);
		tldap_msg_destructor(req);
		tevent_req_error(req, status);
	}
}

static int tldap_msg_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
			  struct tldap_message **pmsg)
{
	struct tldap_msg_state *state = tevent_req_data(
		req, struct tldap_msg_state);
	struct tldap_message *msg;
	int err;
	uint8_t msgtype;

	if (tevent_req_is_ldap_error(req, &err)) {
		return err;
	}

	if (!asn1_peek_uint8(state->data, &msgtype)) {
		return TLDAP_PROTOCOL_ERROR;
	}

	if (pmsg == NULL) {
		return TLDAP_SUCCESS;
	}

	msg = talloc_zero(mem_ctx, struct tldap_message);
	if (msg == NULL) {
		return TLDAP_NO_MEMORY;
	}
	msg->id = state->id;

	msg->inbuf = talloc_move(msg, &state->inbuf);
	msg->data = talloc_move(msg, &state->data);
	msg->type = msgtype;

	*pmsg = msg;
	return TLDAP_SUCCESS;
}

struct tldap_req_state {
	int id;
	struct asn1_data *out;
	struct tldap_message *result;
};

static struct tevent_req *tldap_req_create(TALLOC_CTX *mem_ctx,
					   struct tldap_context *ld,
					   struct tldap_req_state **pstate)
{
	struct tevent_req *req;
	struct tldap_req_state *state;

	req = tevent_req_create(mem_ctx, &state, struct tldap_req_state);
	if (req == NULL) {
		return NULL;
	}
	ZERO_STRUCTP(state);
	state->out = asn1_init(state);
	if (state->out == NULL) {
		TALLOC_FREE(req);
		return NULL;
	}
	state->result = NULL;
	state->id = tldap_next_msgid(ld);

	asn1_push_tag(state->out, ASN1_SEQUENCE(0));
	asn1_write_Integer(state->out, state->id);

	*pstate = state;
	return req;
}

static void tldap_save_msg(struct tldap_context *ld, struct tevent_req *req)
{
	struct tldap_req_state *state = tevent_req_data(
		req, struct tldap_req_state);

	TALLOC_FREE(ld->last_msg);
	ld->last_msg = talloc_move(ld, &state->result);
}

static char *blob2string_talloc(TALLOC_CTX *mem_ctx, DATA_BLOB blob)
{
	char *result = talloc_array(mem_ctx, char, blob.length+1);

	if (result == NULL) {
		return NULL;
	}

	memcpy(result, blob.data, blob.length);
	result[blob.length] = '\0';
	return result;
}

static bool asn1_read_OctetString_talloc(TALLOC_CTX *mem_ctx,
					 struct asn1_data *data,
					 char **presult)
{
	DATA_BLOB string;
	char *result;
	if (!asn1_read_OctetString(data, mem_ctx, &string))
		return false;

	result = blob2string_talloc(mem_ctx, string);

	data_blob_free(&string);

	if (result == NULL) {
		return false;
	}
	*presult = result;
	return true;
}

static bool tldap_decode_controls(struct tldap_req_state *state);

static bool tldap_decode_response(struct tldap_req_state *state)
{
	struct asn1_data *data = state->result->data;
	struct tldap_message *msg = state->result;
	bool ok = true;

	ok &= asn1_read_enumerated(data, &msg->lderr);
	ok &= asn1_read_OctetString_talloc(msg, data, &msg->res_matcheddn);
	ok &= asn1_read_OctetString_talloc(msg, data,
					   &msg->res_diagnosticmessage);
	if (asn1_peek_tag(data, ASN1_CONTEXT(3))) {
		ok &= asn1_start_tag(data, ASN1_CONTEXT(3));
		ok &= asn1_read_OctetString_talloc(msg, data,
						   &msg->res_referral);
		ok &= asn1_end_tag(data);
	} else {
		msg->res_referral = NULL;
	}

	return ok;
}

static void tldap_sasl_bind_done(struct tevent_req *subreq);

struct tevent_req *tldap_sasl_bind_send(TALLOC_CTX *mem_ctx,
					struct tevent_context *ev,
					struct tldap_context *ld,
					const char *dn,
					const char *mechanism,
					DATA_BLOB *creds,
					struct tldap_control *sctrls,
					int num_sctrls,
					struct tldap_control *cctrls,
					int num_cctrls)
{
	struct tevent_req *req, *subreq;
	struct tldap_req_state *state;

	req = tldap_req_create(mem_ctx, ld, &state);
	if (req == NULL) {
		return NULL;
	}

	if (dn == NULL) {
		dn = "";
	}

	asn1_push_tag(state->out, TLDAP_REQ_BIND);
	asn1_write_Integer(state->out, ld->ld_version);
	asn1_write_OctetString(state->out, dn, (dn != NULL) ? strlen(dn) : 0);

	if (mechanism == NULL) {
		asn1_push_tag(state->out, ASN1_CONTEXT_SIMPLE(0));
		asn1_write(state->out, creds->data, creds->length);
		asn1_pop_tag(state->out);
	} else {
		asn1_push_tag(state->out, ASN1_CONTEXT(3));
		asn1_write_OctetString(state->out, mechanism,
				       strlen(mechanism));
		if ((creds != NULL) && (creds->data != NULL)) {
			asn1_write_OctetString(state->out, creds->data,
					       creds->length);
		}
		asn1_pop_tag(state->out);
	}

	if (!asn1_pop_tag(state->out)) {
		tevent_req_error(req, TLDAP_ENCODING_ERROR);
		return tevent_req_post(req, ev);
	}

	subreq = tldap_msg_send(state, ev, ld, state->id, state->out,
				sctrls, num_sctrls);
	if (tevent_req_nomem(subreq, req)) {
		return tevent_req_post(req, ev);
	}
	tevent_req_set_callback(subreq, tldap_sasl_bind_done, req);
	return req;
}

static void tldap_sasl_bind_done(struct tevent_req *subreq)
{
	struct tevent_req *req = tevent_req_callback_data(
		subreq, struct tevent_req);
	struct tldap_req_state *state = tevent_req_data(
		req, struct tldap_req_state);
	int err;

	err = tldap_msg_recv(subreq, state, &state->result);
	TALLOC_FREE(subreq);
	if (err != TLDAP_SUCCESS) {
		tevent_req_error(req, err);
		return;
	}
	if (state->result->type != TLDAP_RES_BIND) {
		tevent_req_error(req, TLDAP_PROTOCOL_ERROR);
		return;
	}
	if (!asn1_start_tag(state->result->data, state->result->type) ||
	    !tldap_decode_response(state) ||
	    !asn1_end_tag(state->result->data)) {
		tevent_req_error(req, TLDAP_DECODING_ERROR);
		return;
	}
	/*
	 * TODO: pull the reply blob
	 */
	if (state->result->lderr != TLDAP_SUCCESS) {
		tevent_req_error(req, state->result->lderr);
		return;
	}
	tevent_req_done(req);
}

int tldap_sasl_bind_recv(struct tevent_req *req)
{
	return tldap_simple_recv(req);
}

int tldap_sasl_bind(struct tldap_context *ld,
		    const char *dn,
		    const char *mechanism,
		    DATA_BLOB *creds,
		    struct tldap_control *sctrls,
		    int num_sctrls,
		    struct tldap_control *cctrls,
		    int num_cctrls)
{
	TALLOC_CTX *frame = talloc_stackframe();
	struct tevent_context *ev;
	struct tevent_req *req;
	int result;

	ev = event_context_init(frame);
	if (ev == NULL) {
		result = TLDAP_NO_MEMORY;
		goto fail;
	}

	req = tldap_sasl_bind_send(frame, ev, ld, dn, mechanism, creds,
				   sctrls, num_sctrls, cctrls, num_cctrls);
	if (req == NULL) {
		result = TLDAP_NO_MEMORY;
		goto fail;
	}

	if (!tevent_req_poll(req, ev)) {
		result = TLDAP_OPERATIONS_ERROR;
		goto fail;
	}

	result = tldap_sasl_bind_recv(req);
	tldap_save_msg(ld, req);
 fail:
	TALLOC_FREE(frame);
	return result;
}

struct tevent_req *tldap_simple_bind_send(TALLOC_CTX *mem_ctx,
					  struct tevent_context *ev,
					  struct tldap_context *ld,
					  const char *dn,
					  const char *passwd)
{
	DATA_BLOB cred;

	if (passwd != NULL) {
		cred.data = discard_const_p(uint8_t, passwd);
		cred.length = strlen(passwd);
	} else {
		cred.data = discard_const_p(uint8_t, "");
		cred.length = 0;
	}
	return tldap_sasl_bind_send(mem_ctx, ev, ld, dn, NULL, &cred, NULL, 0,
				    NULL, 0);
}

int tldap_simple_bind_recv(struct tevent_req *req)
{
	return tldap_sasl_bind_recv(req);
}

int tldap_simple_bind(struct tldap_context *ld, const char *dn,
		      const char *passwd)
{
	DATA_BLOB cred;

	if (passwd != NULL) {
		cred.data = discard_const_p(uint8_t, passwd);
		cred.length = strlen(passwd);
	} else {
		cred.data = discard_const_p(uint8_t, "");
		cred.length = 0;
	}
	return tldap_sasl_bind(ld, dn, NULL, &cred, NULL, 0, NULL, 0);
}

/*****************************************************************************/

/* can't use isalpha() as only a strict set is valid for LDAP */

static bool tldap_is_alpha(char c)
{
	return (((c >= 'a') && (c <= 'z')) || \
		((c >= 'A') && (c <= 'Z')));
}

static bool tldap_is_adh(char c)
{
	return tldap_is_alpha(c) || isdigit(c) || (c == '-');
}

#define TLDAP_FILTER_AND  ASN1_CONTEXT(0)
#define TLDAP_FILTER_OR   ASN1_CONTEXT(1)
#define TLDAP_FILTER_NOT  ASN1_CONTEXT(2)
#define TLDAP_FILTER_EQ   ASN1_CONTEXT(3)
#define TLDAP_FILTER_SUB  ASN1_CONTEXT(4)
#define TLDAP_FILTER_LE   ASN1_CONTEXT(5)
#define TLDAP_FILTER_GE   ASN1_CONTEXT(6)
#define TLDAP_FILTER_PRES ASN1_CONTEXT_SIMPLE(7)
#define TLDAP_FILTER_APX  ASN1_CONTEXT(8)
#define TLDAP_FILTER_EXT  ASN1_CONTEXT(9)

#define TLDAP_SUB_INI ASN1_CONTEXT_SIMPLE(0)
#define TLDAP_SUB_ANY ASN1_CONTEXT_SIMPLE(1)
#define TLDAP_SUB_FIN ASN1_CONTEXT_SIMPLE(2)


/* oid's should be numerical only in theory,
 * but apparently some broken servers may have alphanum aliases instead.
 * Do like openldap libraries and allow alphanum aliases for oids, but
 * do not allow Tagging options in that case.
 */
static bool tldap_is_attrdesc(const char *s, int len, bool no_tagopts)
{
	bool is_oid = false;
	bool dot = false;
	int i;

	/* first char has stricter rules */
	if (isdigit(*s)) {
		is_oid = true;
	} else if (!tldap_is_alpha(*s)) {
		/* bad first char */
		return false;
	}

	for (i = 1; i < len; i++) {

		if (is_oid) {
			if (isdigit(s[i])) {
				dot = false;
				continue;
			}
			if (s[i] == '.') {
				if (dot) {
					/* malformed */
					return false;
				}
				dot = true;
				continue;
			}
		} else {
			if (tldap_is_adh(s[i])) {
				continue;
			}
		}

		if (s[i] == ';') {
			if (no_tagopts) {
				/* no tagging options */
				return false;
			}
			if (dot) {
				/* malformed */
				return false;
			}
			if ((i + 1) == len) {
				/* malformed */
				return false;
			}

			is_oid = false;
			continue;
		}
	}

	if (dot) {
		/* malformed */
		return false;
	}

	return true;
}

/* this function copies the value until the closing parenthesis is found. */
static char *tldap_get_val(TALLOC_CTX *memctx,
			   const char *value, const char **_s)
{
	const char *s = value;

	/* find terminator */
	while (*s) {
		s = strchr(s, ')');
		if (s && (*(s - 1) == '\\')) {
			continue;
		}
		break;
	}
	if (!s || !(*s == ')')) {
		/* malformed filter */
		return NULL;
	}

	*_s = s;

	return talloc_strndup(memctx, value, s - value);
}

static int tldap_hex2char(const char *x)
{
	if (isxdigit(x[0]) && isxdigit(x[1])) {
		const char h1 = x[0], h2 = x[1];
		int c = 0;

		if (h1 >= 'a') c = h1 - (int)'a' + 10;
		else if (h1 >= 'A') c = h1 - (int)'A' + 10;
		else if (h1 >= '0') c = h1 - (int)'0';
		c = c << 4;
		if (h2 >= 'a') c += h2 - (int)'a' + 10;
		else if (h2 >= 'A') c += h2 - (int)'A' + 10;
		else if (h2 >= '0') c += h2 - (int)'0';

		return c;
	}

	return -1;
}

static bool tldap_find_first_star(const char *val, const char **star)
{
	const char *s;

	for (s = val; *s; s++) {
		switch (*s) {
		case '\\':
			if (isxdigit(s[1]) && isxdigit(s[2])) {
				s += 2;
				break;
			}
			/* not hex based escape, check older syntax */
			switch (s[1]) {
			case '(':
			case ')':
			case '*':
			case '\\':
				s++;
				break;
			default:
				/* invalid escape sequence */
				return false;
			}
			break;
		case ')':
			/* end of val, nothing found */
			*star = s;
			return true;

		case '*':
			*star = s;
			return true;
		}
	}

	/* string ended without closing parenthesis, filter is malformed */
	return false;
}

static bool tldap_unescape_inplace(char *value, size_t *val_len)
{
	int c, i, p;

	for (i = 0,p = 0; i < *val_len; i++) {

		switch (value[i]) {
		case '(':
		case ')':
		case '*':
			/* these must be escaped */
			return false;

		case '\\':
			if (!value[i + 1]) {
				/* invalid EOL */
				return false;
			}
			i++;

			c = tldap_hex2char(&value[i]);
			if (c >= 0 && c < 256) {
				value[p] = c;
				i++;
				p++;
				break;
			}

			switch (value[i]) {
			case '(':
			case ')':
			case '*':
			case '\\':
				value[p] = value[i];
				p++;
			default:
				/* invalid */
				return false;
			}
			break;

		default:
			value[p] = value[i];
			p++;
		}
	}
	value[p] = '\0';
	*val_len = p;
	return true;
}

static bool tldap_push_filter_basic(struct tldap_context *ld,
				    struct asn1_data *data,
				    const char **_s);
static bool tldap_push_filter_substring(struct tldap_context *ld,
					struct asn1_data *data,
					const char *val,
					const char **_s);
static bool tldap_push_filter_int(struct tldap_context *ld,
				  struct asn1_data *data,
				  const char **_s)
{
	const char *s = *_s;
	bool ret;

	if (*s != '(') {
		tldap_debug(ld, TLDAP_DEBUG_ERROR,
			    "Incomplete or malformed filter\n");
		return false;
	}
	s++;

	/* we are right after a parenthesis,
	 * find out what op we have at hand */
	switch (*s) {
	case '&':
		tldap_debug(ld, TLDAP_DEBUG_TRACE, "Filter op: AND\n");
		asn1_push_tag(data, TLDAP_FILTER_AND);
		s++;
		break;

	case '|':
		tldap_debug(ld, TLDAP_DEBUG_TRACE, "Filter op: OR\n");
		asn1_push_tag(data, TLDAP_FILTER_OR);
		s++;
		break;

	case '!':
		tldap_debug(ld, TLDAP_DEBUG_TRACE, "Filter op: NOT\n");
		asn1_push_tag(data, TLDAP_FILTER_NOT);
		s++;
		ret = tldap_push_filter_int(ld, data, &s);
		if (!ret) {
			return false;
		}
		asn1_pop_tag(data);
		goto done;

	case '(':
	case ')':
		tldap_debug(ld, TLDAP_DEBUG_ERROR,
			    "Invalid parenthesis '%c'\n", *s);
		return false;

	case '\0':
		tldap_debug(ld, TLDAP_DEBUG_ERROR,
			    "Invalid filter termination\n");
		return false;

	default:
		ret = tldap_push_filter_basic(ld, data, &s);
		if (!ret) {
			return false;
		}
		goto done;
	}

	/* only and/or filters get here.
	 * go through the list of filters */

	if (*s == ')') {
		/* RFC 4526: empty and/or */
		asn1_pop_tag(data);
		goto done;
	}

	while (*s) {
		ret = tldap_push_filter_int(ld, data, &s);
		if (!ret) {
			return false;
		}

		if (*s == ')') {
			/* end of list, return */
			asn1_pop_tag(data);
			break;
		}
	}

done:
	if (*s != ')') {
		tldap_debug(ld, TLDAP_DEBUG_ERROR,
			    "Incomplete or malformed filter\n");
		return false;
	}
	s++;

	if (data->has_error) {
		return false;
	}

	*_s = s;
	return true;
}


static bool tldap_push_filter_basic(struct tldap_context *ld,
				    struct asn1_data *data,
				    const char **_s)
{
	TALLOC_CTX *tmpctx = talloc_tos();
	const char *s = *_s;
	const char *e;
	const char *eq;
	const char *val;
	const char *type;
	const char *dn;
	const char *rule;
	const char *star;
	size_t type_len = 0;
	char *uval;
	size_t uval_len;
	bool write_octect = true;
	bool ret;

	eq = strchr(s, '=');
	if (!eq) {
		tldap_debug(ld, TLDAP_DEBUG_ERROR,
			    "Invalid filter, missing equal sign\n");
		return false;
	}

	val = eq + 1;
	e = eq - 1;

	switch (*e) {
	case '<':
		asn1_push_tag(data, TLDAP_FILTER_LE);
		break;

	case '>':
		asn1_push_tag(data, TLDAP_FILTER_GE);
		break;

	case '~':
		asn1_push_tag(data, TLDAP_FILTER_APX);
		break;

	case ':':
		asn1_push_tag(data, TLDAP_FILTER_EXT);
		write_octect = false;

		type = NULL;
		dn = NULL;
		rule = NULL;

		if (*s == ':') { /* [:dn]:rule:= value */
			if (s == e) {
				/* malformed filter */
				return false;
			}
			dn = s;
		} else { /* type[:dn][:rule]:= value */
			type = s;
			dn = strchr(s, ':');
			type_len = dn - type;
			if (dn == e) { /* type:= value */
				dn = NULL;
			}
		}
		if (dn) {
			dn++;

			rule = strchr(dn, ':');
			if ((rule == dn + 1) || rule + 1 == e) {
				/* malformed filter, contains "::" */
				return false;
			}

			if (strncasecmp_m(dn, "dn:", 3) != 0) {
				if (rule == e) {
					rule = dn;
					dn = NULL;
				} else {
					/* malformed filter. With two
					 * optionals, the first must be "dn"
					 */
					return false;
				}
			} else {
				if (rule == e) {
					rule = NULL;
				} else {
					rule++;
				}
			}
		}

		if (!type && !dn && !rule) {
			/* malformed filter, there must be at least one */
			return false;
		}

		/*
		  MatchingRuleAssertion ::= SEQUENCE {
		  matchingRule    [1] MatchingRuleID OPTIONAL,
		  type	    [2] AttributeDescription OPTIONAL,
		  matchValue      [3] AssertionValue,
		  dnAttributes    [4] BOOLEAN DEFAULT FALSE
		  }
		*/

		/* check and add rule */
		if (rule) {
			ret = tldap_is_attrdesc(rule, e - rule, true);
			if (!ret) {
				return false;
			}
			asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(1));
			asn1_write(data, rule, e - rule);
			asn1_pop_tag(data);
		}

		/* check and add type */
		if (type) {
			ret = tldap_is_attrdesc(type, type_len, false);
			if (!ret) {
				return false;
			}
			asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(2));
			asn1_write(data, type, type_len);
			asn1_pop_tag(data);
		}

		uval = tldap_get_val(tmpctx, val, _s);
		if (!uval) {
			return false;
		}
		uval_len = *_s - val;
		ret = tldap_unescape_inplace(uval, &uval_len);
		if (!ret) {
			return false;
		}

		asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(3));
		asn1_write(data, uval, uval_len);
		asn1_pop_tag(data);

		asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(4));
		asn1_write_uint8(data, dn?1:0);
		asn1_pop_tag(data);
		break;

	default:
		e = eq;

		ret = tldap_is_attrdesc(s, e - s, false);
		if (!ret) {
			return false;
		}

		if (strncmp(val, "*)", 2) == 0) {
			/* presence */
			asn1_push_tag(data, TLDAP_FILTER_PRES);
			asn1_write(data, s, e - s);
			*_s = val + 1;
			write_octect = false;
			break;
		}

		ret = tldap_find_first_star(val, &star);
		if (!ret) {
			return false;
		}
		if (*star == '*') {
			/* substring */
			asn1_push_tag(data, TLDAP_FILTER_SUB);
			asn1_write_OctetString(data, s, e - s);
			ret = tldap_push_filter_substring(ld, data, val, &s);
			if (!ret) {
				return false;
			}
			*_s = s;
			write_octect = false;
			break;
		}

		/* if nothing else, then it is just equality */
		asn1_push_tag(data, TLDAP_FILTER_EQ);
		write_octect = true;
		break;
	}

	if (write_octect) {
		uval = tldap_get_val(tmpctx, val, _s);
		if (!uval) {
			return false;
		}
		uval_len = *_s - val;
		ret = tldap_unescape_inplace(uval, &uval_len);
		if (!ret) {
			return false;
		}

		asn1_write_OctetString(data, s, e - s);
		asn1_write_OctetString(data, uval, uval_len);
	}

	if (data->has_error) {
		return false;
	}
	asn1_pop_tag(data);
	return true;
}

static bool tldap_push_filter_substring(struct tldap_context *ld,
					struct asn1_data *data,
					const char *val,
					const char **_s)
{
	TALLOC_CTX *tmpctx = talloc_tos();
	bool initial = true;
	const char *star;
	char *chunk;
	size_t chunk_len;
	bool ret;

	/*
	  SubstringFilter ::= SEQUENCE {
		  type	    AttributeDescription,
		  -- at least one must be present
		  substrings      SEQUENCE OF CHOICE {
			  initial [0] LDAPString,
			  any     [1] LDAPString,
			  final   [2] LDAPString } }
	*/
	asn1_push_tag(data, ASN1_SEQUENCE(0));

	do {
		ret = tldap_find_first_star(val, &star);
		if (!ret) {
			return false;
		}
		chunk_len = star - val;

		switch (*star) {
		case '*':
			if (!initial && chunk_len == 0) {
				/* found '**', which is illegal */
				return false;
			}
			break;
		case ')':
			if (initial) {
				/* no stars ?? */
				return false;
			}
			/* we are done */
			break;
		default:
			/* ?? */
			return false;
		}

		if (initial && chunk_len == 0) {
			val = star + 1;
			initial = false;
			continue;
		}

		chunk = talloc_strndup(tmpctx, val, chunk_len);
		if (!chunk) {
			return false;
		}
		ret = tldap_unescape_inplace(chunk, &chunk_len);
		if (!ret) {
			return false;
		}
		switch (*star) {
		case '*':
			if (initial) {
				asn1_push_tag(data, TLDAP_SUB_INI);
				initial = false;
			} else {
				asn1_push_tag(data, TLDAP_SUB_ANY);
			}
			break;
		case ')':
			asn1_push_tag(data, TLDAP_SUB_FIN);
			break;
		default:
			/* ?? */
			return false;
		}
		asn1_write(data, chunk, chunk_len);
		asn1_pop_tag(data);

		val = star + 1;

	} while (*star == '*');

	*_s = star;

	/* end of sequence */
	asn1_pop_tag(data);
	return true;
}

/* NOTE: although openldap libraries allow for spaces in some places, mosly
 * around parenthesis, we do not allow any spaces (except in values of
 * course) as I couldn't fine any place in RFC 4512 or RFC 4515 where
 * leading or trailing spaces where allowed.
 */
static bool tldap_push_filter(struct tldap_context *ld,
			      struct asn1_data *data,
			      const char *filter)
{
	const char *s = filter;
	bool ret;

	ret = tldap_push_filter_int(ld, data, &s);
	if (ret && *s) {
		tldap_debug(ld, TLDAP_DEBUG_ERROR,
			    "Incomplete or malformed filter\n");
		return false;
	}
	return ret;
}

/*****************************************************************************/

static void tldap_search_done(struct tevent_req *subreq);

struct tevent_req *tldap_search_send(TALLOC_CTX *mem_ctx,
				     struct tevent_context *ev,
				     struct tldap_context *ld,
				     const char *base, int scope,
				     const char *filter,
				     const char **attrs,
				     int num_attrs,
				     int attrsonly,
				     struct tldap_control *sctrls,
				     int num_sctrls,
				     struct tldap_control *cctrls,
				     int num_cctrls,
				     int timelimit,
				     int sizelimit,
				     int deref)
{
	struct tevent_req *req, *subreq;
	struct tldap_req_state *state;
	int i;

	req = tldap_req_create(mem_ctx, ld, &state);
	if (req == NULL) {
		return NULL;
	}

	asn1_push_tag(state->out, TLDAP_REQ_SEARCH);
	asn1_write_OctetString(state->out, base, strlen(base));
	asn1_write_enumerated(state->out, scope);
	asn1_write_enumerated(state->out, deref);
	asn1_write_Integer(state->out, sizelimit);
	asn1_write_Integer(state->out, timelimit);
	asn1_write_BOOLEAN(state->out, attrsonly);

	if (!tldap_push_filter(ld, state->out, filter)) {
		goto encoding_error;
	}

	asn1_push_tag(state->out, ASN1_SEQUENCE(0));
	for (i=0; i<num_attrs; i++) {
		asn1_write_OctetString(state->out, attrs[i], strlen(attrs[i]));
	}
	asn1_pop_tag(state->out);
	asn1_pop_tag(state->out);

	subreq = tldap_msg_send(state, ev, ld, state->id, state->out,
				sctrls, num_sctrls);
	if (tevent_req_nomem(subreq, req)) {
		return tevent_req_post(req, ev);
	}
	tevent_req_set_callback(subreq, tldap_search_done, req);
	return req;

 encoding_error:
	tevent_req_error(req, TLDAP_ENCODING_ERROR);
	return tevent_req_post(req, ev);
}

static void tldap_search_done(struct tevent_req *subreq)
{
	struct tevent_req *req = tevent_req_callback_data(
		subreq, struct tevent_req);
	struct tldap_req_state *state = tevent_req_data(
		req, struct tldap_req_state);
	int err;

	err = tldap_msg_recv(subreq, state, &state->result);
	if (err != TLDAP_SUCCESS) {
		tevent_req_error(req, err);
		return;
	}
	switch (state->result->type) {
	case TLDAP_RES_SEARCH_ENTRY:
	case TLDAP_RES_SEARCH_REFERENCE:
		if (!tldap_msg_set_pending(subreq)) {
			tevent_req_oom(req);
			return;
		}
		tevent_req_notify_callback(req);
		break;
	case TLDAP_RES_SEARCH_RESULT:
		TALLOC_FREE(subreq);
		if (!asn1_start_tag(state->result->data,
				    state->result->type) ||
		    !tldap_decode_response(state) ||
		    !asn1_end_tag(state->result->data) ||
		    !tldap_decode_controls(state)) {
			tevent_req_error(req, TLDAP_DECODING_ERROR);
			return;
		}
		tevent_req_done(req);
		break;
	default:
		tevent_req_error(req, TLDAP_PROTOCOL_ERROR);
		return;
	}
}

int tldap_search_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
		      struct tldap_message **pmsg)
{
	struct tldap_req_state *state = tevent_req_data(
		req, struct tldap_req_state);
	int err;

	if (!tevent_req_is_in_progress(req)
	    && tevent_req_is_ldap_error(req, &err)) {
		return err;
	}

	if (tevent_req_is_in_progress(req)) {
		switch (state->result->type) {
		case TLDAP_RES_SEARCH_ENTRY:
		case TLDAP_RES_SEARCH_REFERENCE:
			break;
		default:
			return TLDAP_OPERATIONS_ERROR;
		}
	}

	*pmsg = talloc_move(mem_ctx, &state->result);
	return TLDAP_SUCCESS;
}

struct tldap_sync_search_state {
	TALLOC_CTX *mem_ctx;
	struct tldap_message **entries;
	struct tldap_message **refs;
	int rc;
};

static void tldap_search_cb(struct tevent_req *req)
{
	struct tldap_sync_search_state *state =
		(struct tldap_sync_search_state *)
		tevent_req_callback_data_void(req);
	struct tldap_message *msg, **tmp;
	int rc, num_entries, num_refs;

	rc = tldap_search_recv(req, talloc_tos(), &msg);
	if (rc != TLDAP_SUCCESS) {
		state->rc = rc;
		return;
	}

	switch (tldap_msg_type(msg)) {
	case TLDAP_RES_SEARCH_ENTRY:
		num_entries = talloc_array_length(state->entries);
		tmp = talloc_realloc(state->mem_ctx, state->entries,
				     struct tldap_message *, num_entries + 1);
		if (tmp == NULL) {
			state->rc = TLDAP_NO_MEMORY;
			return;
		}
		state->entries = tmp;
		state->entries[num_entries] = talloc_move(state->entries,
							  &msg);
		break;
	case TLDAP_RES_SEARCH_REFERENCE:
		num_refs = talloc_array_length(state->refs);
		tmp = talloc_realloc(state->mem_ctx, state->refs,
				     struct tldap_message *, num_refs + 1);
		if (tmp == NULL) {
			state->rc = TLDAP_NO_MEMORY;
			return;
		}
		state->refs = tmp;
		state->refs[num_refs] = talloc_move(state->refs, &msg);
		break;
	case TLDAP_RES_SEARCH_RESULT:
		state->rc = TLDAP_SUCCESS;
		break;
	default:
		state->rc = TLDAP_PROTOCOL_ERROR;
		break;
	}
}

int tldap_search(struct tldap_context *ld,
		 const char *base, int scope, const char *filter,
		 const char **attrs, int num_attrs, int attrsonly,
		 struct tldap_control *sctrls, int num_sctrls,
		 struct tldap_control *cctrls, int num_cctrls,
		 int timelimit, int sizelimit, int deref,
		 TALLOC_CTX *mem_ctx, struct tldap_message ***entries,
		 struct tldap_message ***refs)
{
	TALLOC_CTX *frame = talloc_stackframe();
	struct tevent_context *ev;
	struct tevent_req *req;
	struct tldap_sync_search_state state;

	ZERO_STRUCT(state);
	state.mem_ctx = mem_ctx;
	state.rc = TLDAP_SUCCESS;

	ev = event_context_init(frame);
	if (ev == NULL) {
		state.rc = TLDAP_NO_MEMORY;
		goto fail;
	}

	req = tldap_search_send(frame, ev, ld, base, scope, filter,
				attrs, num_attrs, attrsonly,
				sctrls, num_sctrls, cctrls, num_cctrls,
				timelimit, sizelimit, deref);
	if (req == NULL) {
		state.rc = TLDAP_NO_MEMORY;
		goto fail;
	}

	tevent_req_set_callback(req, tldap_search_cb, &state);

	if (!tevent_req_is_in_progress(req)) {
		/* an error happend before sending */
		if (tevent_req_is_ldap_error(req, &state.rc)) {
			goto fail;
		}
	}

	while (tevent_req_is_in_progress(req)
	       && (state.rc == TLDAP_SUCCESS)) {
		if (tevent_loop_once(ev) == -1) {
			return TLDAP_OPERATIONS_ERROR;
		}
	}

	if (state.rc != TLDAP_SUCCESS) {
		return state.rc;
	}

	if (entries != NULL) {
		*entries = state.entries;
	} else {
		TALLOC_FREE(state.entries);
	}
	if (refs != NULL) {
		*refs = state.refs;
	} else {
		TALLOC_FREE(state.refs);
	}
	tldap_save_msg(ld, req);
fail:
	TALLOC_FREE(frame);
	return state.rc;
}

static bool tldap_parse_search_entry(struct tldap_message *msg)
{
	int num_attribs = 0;

	asn1_start_tag(msg->data, msg->type);

	/* dn */

	asn1_read_OctetString_talloc(msg, msg->data, &msg->dn);
	if (msg->dn == NULL) {
		return false;
	}

	/*
	 * Attributes: We overallocate msg->attribs by one, so that while
	 * looping over the attributes we can directly parse into the last
	 * array element. Same for the values in the inner loop.
	 */

	msg->attribs = talloc_array(msg, struct tldap_attribute, 1);
	if (msg->attribs == NULL) {
		return false;
	}

	asn1_start_tag(msg->data, ASN1_SEQUENCE(0));
	while (asn1_peek_tag(msg->data, ASN1_SEQUENCE(0))) {
		struct tldap_attribute *attrib;
		int num_values = 0;

		attrib = &msg->attribs[num_attribs];
		attrib->values = talloc_array(msg->attribs, DATA_BLOB, 1);
		if (attrib->values == NULL) {
			return false;
		}
		asn1_start_tag(msg->data, ASN1_SEQUENCE(0));
		asn1_read_OctetString_talloc(msg->attribs, msg->data,
					     &attrib->name);
		asn1_start_tag(msg->data, ASN1_SET);

		while (asn1_peek_tag(msg->data, ASN1_OCTET_STRING)) {
			asn1_read_OctetString(msg->data, msg,
					      &attrib->values[num_values]);

			attrib->values = talloc_realloc(
				msg->attribs, attrib->values, DATA_BLOB,
				num_values + 2);
			if (attrib->values == NULL) {
				return false;
			}
			num_values += 1;
		}
		attrib->values = talloc_realloc(msg->attribs, attrib->values,
						DATA_BLOB, num_values);
		attrib->num_values = num_values;

		asn1_end_tag(msg->data); /* ASN1_SET */
		asn1_end_tag(msg->data); /* ASN1_SEQUENCE(0) */
		msg->attribs = talloc_realloc(
			msg, msg->attribs, struct tldap_attribute,
			num_attribs + 2);
		if (msg->attribs == NULL) {
			return false;
		}
		num_attribs += 1;
	}
	msg->attribs = talloc_realloc(
		msg, msg->attribs, struct tldap_attribute, num_attribs);
	asn1_end_tag(msg->data);
	if (msg->data->has_error) {
		return false;
	}
	return true;
}

bool tldap_entry_dn(struct tldap_message *msg, char **dn)
{
	if ((msg->dn == NULL) && (!tldap_parse_search_entry(msg))) {
		return false;
	}
	*dn = msg->dn;
	return true;
}

bool tldap_entry_attributes(struct tldap_message *msg,
			    struct tldap_attribute **attributes,
			    int *num_attributes)
{
	if ((msg->dn == NULL) && (!tldap_parse_search_entry(msg))) {
		return false;
	}
	*attributes = msg->attribs;
	*num_attributes = talloc_array_length(msg->attribs);
	return true;
}

static bool tldap_decode_controls(struct tldap_req_state *state)
{
	struct tldap_message *msg = state->result;
	struct asn1_data *data = msg->data;
	struct tldap_control *sctrls = NULL;
	int num_controls = 0;

	msg->res_sctrls = NULL;

	if (!asn1_peek_tag(data, ASN1_CONTEXT(0))) {
		return true;
	}

	asn1_start_tag(data, ASN1_CONTEXT(0));

	while (asn1_peek_tag(data, ASN1_SEQUENCE(0))) {
		struct tldap_control *c;
		char *oid = NULL;

		sctrls = talloc_realloc(msg, sctrls, struct tldap_control,
					num_controls + 1);
		if (sctrls == NULL) {
			return false;
		}
		c = &sctrls[num_controls];

		asn1_start_tag(data, ASN1_SEQUENCE(0));
		asn1_read_OctetString_talloc(msg, data, &oid);
		if ((data->has_error) || (oid == NULL)) {
			return false;
		}
		c->oid = oid;
		if (asn1_peek_tag(data, ASN1_BOOLEAN)) {
			asn1_read_BOOLEAN(data, &c->critical);
		} else {
			c->critical = false;
		}
		c->value = data_blob_null;
		if (asn1_peek_tag(data, ASN1_OCTET_STRING) &&
		    !asn1_read_OctetString(data, msg, &c->value)) {
			return false;
		}
		asn1_end_tag(data); /* ASN1_SEQUENCE(0) */

		num_controls += 1;
	}

	asn1_end_tag(data); 	/* ASN1_CONTEXT(0) */

	if (data->has_error) {
		TALLOC_FREE(sctrls);
		return false;
	}
	msg->res_sctrls = sctrls;
	return true;
}

static void tldap_simple_done(struct tevent_req *subreq, int type)
{
	struct tevent_req *req = tevent_req_callback_data(
		subreq, struct tevent_req);
	struct tldap_req_state *state = tevent_req_data(
		req, struct tldap_req_state);
	int err;

	err = tldap_msg_recv(subreq, state, &state->result);
	TALLOC_FREE(subreq);
	if (err != TLDAP_SUCCESS) {
		tevent_req_error(req, err);
		return;
	}
	if (state->result->type != type) {
		tevent_req_error(req, TLDAP_PROTOCOL_ERROR);
		return;
	}
	if (!asn1_start_tag(state->result->data, state->result->type) ||
	    !tldap_decode_response(state) ||
	    !asn1_end_tag(state->result->data) ||
	    !tldap_decode_controls(state)) {
		tevent_req_error(req, TLDAP_DECODING_ERROR);
		return;
	}
	if (state->result->lderr != TLDAP_SUCCESS) {
		tevent_req_error(req, state->result->lderr);
		return;
	}
	tevent_req_done(req);
}

static int tldap_simple_recv(struct tevent_req *req)
{
	int err;
	if (tevent_req_is_ldap_error(req, &err)) {
		return err;
	}
	return TLDAP_SUCCESS;
}

static void tldap_add_done(struct tevent_req *subreq);

struct tevent_req *tldap_add_send(TALLOC_CTX *mem_ctx,
				  struct tevent_context *ev,
				  struct tldap_context *ld,
				  const char *dn,
				  struct tldap_mod *attributes,
				  int num_attributes,
				  struct tldap_control *sctrls,
				  int num_sctrls,
				  struct tldap_control *cctrls,
				  int num_cctrls)
{
	struct tevent_req *req, *subreq;
	struct tldap_req_state *state;
	int i, j;

	req = tldap_req_create(mem_ctx, ld, &state);
	if (req == NULL) {
		return NULL;
	}

	asn1_push_tag(state->out, TLDAP_REQ_ADD);
	asn1_write_OctetString(state->out, dn, strlen(dn));
	asn1_push_tag(state->out, ASN1_SEQUENCE(0));

	for (i=0; i<num_attributes; i++) {
		struct tldap_mod *attrib = &attributes[i];
		asn1_push_tag(state->out, ASN1_SEQUENCE(0));
		asn1_write_OctetString(state->out, attrib->attribute,
				       strlen(attrib->attribute));
		asn1_push_tag(state->out, ASN1_SET);
		for (j=0; j<attrib->num_values; j++) {
			asn1_write_OctetString(state->out,
					       attrib->values[j].data,
					       attrib->values[j].length);
		}
		asn1_pop_tag(state->out);
		asn1_pop_tag(state->out);
	}

	asn1_pop_tag(state->out);
	asn1_pop_tag(state->out);

	subreq = tldap_msg_send(state, ev, ld, state->id, state->out,
				sctrls, num_sctrls);
	if (tevent_req_nomem(subreq, req)) {
		return tevent_req_post(req, ev);
	}
	tevent_req_set_callback(subreq, tldap_add_done, req);
	return req;
}

static void tldap_add_done(struct tevent_req *subreq)
{
	tldap_simple_done(subreq, TLDAP_RES_ADD);
}

int tldap_add_recv(struct tevent_req *req)
{
	return tldap_simple_recv(req);
}

int tldap_add(struct tldap_context *ld, const char *dn,
	      struct tldap_mod *attributes, int num_attributes,
	      struct tldap_control *sctrls, int num_sctrls,
	      struct tldap_control *cctrls, int num_cctrls)
{
	TALLOC_CTX *frame = talloc_stackframe();
	struct tevent_context *ev;
	struct tevent_req *req;
	int result;

	ev = event_context_init(frame);
	if (ev == NULL) {
		result = TLDAP_NO_MEMORY;
		goto fail;
	}

	req = tldap_add_send(frame, ev, ld, dn, attributes, num_attributes,
			     sctrls, num_sctrls, cctrls, num_cctrls);
	if (req == NULL) {
		result = TLDAP_NO_MEMORY;
		goto fail;
	}

	if (!tevent_req_poll(req, ev)) {
		result = TLDAP_OPERATIONS_ERROR;
		goto fail;
	}

	result = tldap_add_recv(req);
	tldap_save_msg(ld, req);
 fail:
	TALLOC_FREE(frame);
	return result;
}

static void tldap_modify_done(struct tevent_req *subreq);

struct tevent_req *tldap_modify_send(TALLOC_CTX *mem_ctx,
				     struct tevent_context *ev,
				     struct tldap_context *ld,
				     const char *dn,
				     struct tldap_mod *mods, int num_mods,
				     struct tldap_control *sctrls,
				     int num_sctrls,
				     struct tldap_control *cctrls,
				     int num_cctrls)
{
	struct tevent_req *req, *subreq;
	struct tldap_req_state *state;
	int i, j;

	req = tldap_req_create(mem_ctx, ld, &state);
	if (req == NULL) {
		return NULL;
	}

	asn1_push_tag(state->out, TLDAP_REQ_MODIFY);
	asn1_write_OctetString(state->out, dn, strlen(dn));
	asn1_push_tag(state->out, ASN1_SEQUENCE(0));

	for (i=0; i<num_mods; i++) {
		struct tldap_mod *mod = &mods[i];
		asn1_push_tag(state->out, ASN1_SEQUENCE(0));
		asn1_write_enumerated(state->out, mod->mod_op),
		asn1_push_tag(state->out, ASN1_SEQUENCE(0));
		asn1_write_OctetString(state->out, mod->attribute,
				       strlen(mod->attribute));
		asn1_push_tag(state->out, ASN1_SET);
		for (j=0; j<mod->num_values; j++) {
			asn1_write_OctetString(state->out,
					       mod->values[j].data,
					       mod->values[j].length);
		}
		asn1_pop_tag(state->out);
		asn1_pop_tag(state->out);
		asn1_pop_tag(state->out);
	}

	asn1_pop_tag(state->out);
	asn1_pop_tag(state->out);

	subreq = tldap_msg_send(state, ev, ld, state->id, state->out,
				sctrls, num_sctrls);
	if (tevent_req_nomem(subreq, req)) {
		return tevent_req_post(req, ev);
	}
	tevent_req_set_callback(subreq, tldap_modify_done, req);
	return req;
}

static void tldap_modify_done(struct tevent_req *subreq)
{
	tldap_simple_done(subreq, TLDAP_RES_MODIFY);
}

int tldap_modify_recv(struct tevent_req *req)
{
	return tldap_simple_recv(req);
}

int tldap_modify(struct tldap_context *ld, const char *dn,
		 struct tldap_mod *mods, int num_mods,
		 struct tldap_control *sctrls, int num_sctrls,
		 struct tldap_control *cctrls, int num_cctrls)
 {
	TALLOC_CTX *frame = talloc_stackframe();
	struct tevent_context *ev;
	struct tevent_req *req;
	int result;

	ev = event_context_init(frame);
	if (ev == NULL) {
		result = TLDAP_NO_MEMORY;
		goto fail;
	}

	req = tldap_modify_send(frame, ev, ld, dn, mods, num_mods,
				sctrls, num_sctrls, cctrls, num_cctrls);
	if (req == NULL) {
		result = TLDAP_NO_MEMORY;
		goto fail;
	}

	if (!tevent_req_poll(req, ev)) {
		result = TLDAP_OPERATIONS_ERROR;
		goto fail;
	}

	result = tldap_modify_recv(req);
	tldap_save_msg(ld, req);
 fail:
	TALLOC_FREE(frame);
	return result;
}

static void tldap_delete_done(struct tevent_req *subreq);

struct tevent_req *tldap_delete_send(TALLOC_CTX *mem_ctx,
				     struct tevent_context *ev,
				     struct tldap_context *ld,
				     const char *dn,
				     struct tldap_control *sctrls,
				     int num_sctrls,
				     struct tldap_control *cctrls,
				     int num_cctrls)
{
	struct tevent_req *req, *subreq;
	struct tldap_req_state *state;

	req = tldap_req_create(mem_ctx, ld, &state);
	if (req == NULL) {
		return NULL;
	}

	asn1_push_tag(state->out, TLDAP_REQ_DELETE);
	asn1_write(state->out, dn, strlen(dn));
	asn1_pop_tag(state->out);

	subreq = tldap_msg_send(state, ev, ld, state->id, state->out,
				sctrls, num_sctrls);
	if (tevent_req_nomem(subreq, req)) {
		return tevent_req_post(req, ev);
	}
	tevent_req_set_callback(subreq, tldap_delete_done, req);
	return req;
}

static void tldap_delete_done(struct tevent_req *subreq)
{
	tldap_simple_done(subreq, TLDAP_RES_DELETE);
}

int tldap_delete_recv(struct tevent_req *req)
{
	return tldap_simple_recv(req);
}

int tldap_delete(struct tldap_context *ld, const char *dn,
		 struct tldap_control *sctrls, int num_sctrls,
		 struct tldap_control *cctrls, int num_cctrls)
{
	TALLOC_CTX *frame = talloc_stackframe();
	struct tevent_context *ev;
	struct tevent_req *req;
	int result;

	ev = event_context_init(frame);
	if (ev == NULL) {
		result = TLDAP_NO_MEMORY;
		goto fail;
	}

	req = tldap_delete_send(frame, ev, ld, dn, sctrls, num_sctrls,
				cctrls, num_cctrls);
	if (req == NULL) {
		result = TLDAP_NO_MEMORY;
		goto fail;
	}

	if (!tevent_req_poll(req, ev)) {
		result = TLDAP_OPERATIONS_ERROR;
		goto fail;
	}

	result = tldap_delete_recv(req);
	tldap_save_msg(ld, req);
 fail:
	TALLOC_FREE(frame);
	return result;
}

int tldap_msg_id(const struct tldap_message *msg)
{
	return msg->id;
}

int tldap_msg_type(const struct tldap_message *msg)
{
	return msg->type;
}

const char *tldap_msg_matcheddn(struct tldap_message *msg)
{
	if (msg == NULL) {
		return NULL;
	}
	return msg->res_matcheddn;
}

const char *tldap_msg_diagnosticmessage(struct tldap_message *msg)
{
	if (msg == NULL) {
		return NULL;
	}
	return msg->res_diagnosticmessage;
}

const char *tldap_msg_referral(struct tldap_message *msg)
{
	if (msg == NULL) {
		return NULL;
	}
	return msg->res_referral;
}

void tldap_msg_sctrls(struct tldap_message *msg, int *num_sctrls,
		      struct tldap_control **sctrls)
{
	if (msg == NULL) {
		*sctrls = NULL;
		*num_sctrls = 0;
		return;
	}
	*sctrls = msg->res_sctrls;
	*num_sctrls = talloc_array_length(msg->res_sctrls);
}

struct tldap_message *tldap_ctx_lastmsg(struct tldap_context *ld)
{
	return ld->last_msg;
}

const char *tldap_err2string(int rc)
{
	const char *res = NULL;

	/*
	 * This would normally be a table, but the error codes are not fully
	 * sequential. Let the compiler figure out the optimum implementation
	 * :-)
	 */

	switch (rc) {
	case TLDAP_SUCCESS:
		res = "TLDAP_SUCCESS";
		break;
	case TLDAP_OPERATIONS_ERROR:
		res = "TLDAP_OPERATIONS_ERROR";
		break;
	case TLDAP_PROTOCOL_ERROR:
		res = "TLDAP_PROTOCOL_ERROR";
		break;
	case TLDAP_TIMELIMIT_EXCEEDED:
		res = "TLDAP_TIMELIMIT_EXCEEDED";
		break;
	case TLDAP_SIZELIMIT_EXCEEDED:
		res = "TLDAP_SIZELIMIT_EXCEEDED";
		break;
	case TLDAP_COMPARE_FALSE:
		res = "TLDAP_COMPARE_FALSE";
		break;
	case TLDAP_COMPARE_TRUE:
		res = "TLDAP_COMPARE_TRUE";
		break;
	case TLDAP_STRONG_AUTH_NOT_SUPPORTED:
		res = "TLDAP_STRONG_AUTH_NOT_SUPPORTED";
		break;
	case TLDAP_STRONG_AUTH_REQUIRED:
		res = "TLDAP_STRONG_AUTH_REQUIRED";
		break;
	case TLDAP_REFERRAL:
		res = "TLDAP_REFERRAL";
		break;
	case TLDAP_ADMINLIMIT_EXCEEDED:
		res = "TLDAP_ADMINLIMIT_EXCEEDED";
		break;
	case TLDAP_UNAVAILABLE_CRITICAL_EXTENSION:
		res = "TLDAP_UNAVAILABLE_CRITICAL_EXTENSION";
		break;
	case TLDAP_CONFIDENTIALITY_REQUIRED:
		res = "TLDAP_CONFIDENTIALITY_REQUIRED";
		break;
	case TLDAP_SASL_BIND_IN_PROGRESS:
		res = "TLDAP_SASL_BIND_IN_PROGRESS";
		break;
	case TLDAP_NO_SUCH_ATTRIBUTE:
		res = "TLDAP_NO_SUCH_ATTRIBUTE";
		break;
	case TLDAP_UNDEFINED_TYPE:
		res = "TLDAP_UNDEFINED_TYPE";
		break;
	case TLDAP_INAPPROPRIATE_MATCHING:
		res = "TLDAP_INAPPROPRIATE_MATCHING";
		break;
	case TLDAP_CONSTRAINT_VIOLATION:
		res = "TLDAP_CONSTRAINT_VIOLATION";