Merge branch 'master' of ssh://git.samba.org/data/git/samba into arc4
authorJelmer Vernooij <jelmer@samba.org>
Sat, 11 Oct 2008 12:44:10 +0000 (14:44 +0200)
committerJelmer Vernooij <jelmer@samba.org>
Sat, 11 Oct 2008 12:44:10 +0000 (14:44 +0200)
374 files changed:
.gitignore
README.Coding
docs-xml/manpages-3/idmap_adex.8.xml [new file with mode: 0644]
docs-xml/manpages-3/idmap_hash.8.xml [new file with mode: 0644]
docs-xml/manpages-3/pam_winbind.7.xml
docs-xml/manpages-3/vfs_smb_traffic_analyzer.8.xml [new file with mode: 0644]
docs-xml/smbdotconf/printing/cupsconnectiontimeout.xml [new file with mode: 0644]
docs-xml/smbdotconf/printing/cupstimeout.xml [deleted file]
docs-xml/smbdotconf/winbind/winbindnormalizenames.xml
examples/VFS/skel_opaque.c
examples/VFS/skel_transparent.c
examples/pam_winbind/pam_winbind.conf
lib/socket_wrapper/socket_wrapper.c
lib/subunit/harness2subunit.pl [moved from source4/script/harness2subunit.pl with 100% similarity]
lib/subunit/python/subunit/__init__.py [moved from source4/scripting/python/subunit/__init__.py with 100% similarity]
lib/subunit/python/subunit/tests/TestUtil.py [new file with mode: 0644]
lib/subunit/python/subunit/tests/__init__.py [new file with mode: 0644]
lib/subunit/python/subunit/tests/sample-script.py [new file with mode: 0755]
lib/subunit/python/subunit/tests/sample-two-script.py [new file with mode: 0755]
lib/subunit/python/subunit/tests/test_test_protocol.py [new file with mode: 0644]
lib/talloc/talloc_guide.txt
lib/tdb/configure.ac
libcli/netlogon.c
libcli/netlogon.h
pidl/TODO
pidl/config.mk
pidl/lib/Parse/Pidl/ODL.pm
pidl/lib/Parse/Pidl/Samba4/Python.pm
pidl/tests/samba3-srv.pl [changed mode: 0644->0755]
prog_guide4.txt
source3/Makefile.in
source3/auth/auth_domain.c
source3/auth/auth_netlogond.c [new file with mode: 0644]
source3/autogen.sh
source3/client/client.c
source3/client/mount.cifs.c
source3/configure.in
source3/dynconfig.c
source3/groupdb/mapping_tdb.c
source3/include/dynconfig.h
source3/include/libmsrpc.h [deleted file]
source3/include/libmsrpc_internal.h [deleted file]
source3/include/nameserv.h
source3/include/printing.h
source3/include/proto.h
source3/include/rpc_secdes.h
source3/include/secrets.h
source3/include/smb.h
source3/include/smb_macros.h
source3/include/vfs.h
source3/lib/async_sock.c
source3/lib/ctdbd_conn.c
source3/lib/dbwrap_ctdb.c
source3/lib/debug.c
source3/lib/display_sec.c
source3/lib/dummysmbd.c
source3/lib/errmap_unix.c
source3/lib/ldb/common/ldb.c
source3/lib/netapi/file.c
source3/lib/netapi/getdc.c
source3/lib/netapi/share.c
source3/lib/netapi/user.c
source3/lib/readline.c
source3/lib/secace.c
source3/lib/secdesc.c
source3/lib/sharesec.c
source3/lib/util_seaccess.c
source3/libaddns/dnsmarshall.c
source3/libaddns/dnsrecord.c
source3/libads/cldap.c
source3/libads/ldap.c
source3/libads/util.c
source3/libgpo/gpext/scripts.c
source3/libgpo/gpext/security.c [new file with mode: 0644]
source3/libgpo/gpo_reg.c
source3/libnet/libnet_join.c
source3/libnet/libnet_proto.h
source3/librpc/gen_ndr/nbt.h
source3/librpc/gen_ndr/ndr_nbt.c
source3/librpc/idl/nbt.idl
source3/libsmb/async_smb.c
source3/libsmb/clidgram.c
source3/libsmb/clierror.c
source3/libsmb/cliquota.c
source3/libsmb/dsgetdcname.c
source3/libsmb/libsmb_xattr.c
source3/m4/check_path.m4
source3/modules/nfs4_acls.c
source3/modules/vfs_acl_xattr.c
source3/modules/vfs_afsacl.c
source3/modules/vfs_aixacl2.c
source3/modules/vfs_default.c
source3/modules/vfs_full_audit.c
source3/modules/vfs_gpfs.c
source3/modules/vfs_smb_traffic_analyzer.c [new file with mode: 0644]
source3/modules/vfs_zfsacl.c
source3/nmbd/nmbd_processlogon.c
source3/nsswitch/libwbclient/wbc_guid.c [new file with mode: 0644]
source3/nsswitch/libwbclient/wbc_idmap.c
source3/nsswitch/libwbclient/wbc_pam.c
source3/nsswitch/libwbclient/wbc_pwd.c
source3/nsswitch/libwbclient/wbc_sid.c
source3/nsswitch/libwbclient/wbc_util.c
source3/nsswitch/libwbclient/wbclient.h
source3/nsswitch/pam_winbind.c
source3/nsswitch/pam_winbind.h
source3/nsswitch/wbinfo.c
source3/nsswitch/winbind_krb5_locator.c
source3/nsswitch/winbind_struct_protocol.h
source3/param/loadparm.c
source3/param/test_lp_load.c [new file with mode: 0644]
source3/passdb/secrets.c
source3/printing/load.c
source3/printing/notify.c
source3/printing/nt_printing.c
source3/printing/pcap.c
source3/printing/print_cups.c
source3/registry/reg_dispatcher.c
source3/rpc_server/srv_lsa_nt.c
source3/rpc_server/srv_samr_nt.c
source3/rpc_server/srv_srvsvc_nt.c
source3/rpc_server/srv_svcctl_nt.c
source3/samba4.m4
source3/samba4.mk
source3/script/tests/wb_pad.sh [new file with mode: 0755]
source3/services/services_db.c
source3/smbd/conn.c
source3/smbd/connection.c
source3/smbd/fake_file.c
source3/smbd/files.c
source3/smbd/ipc.c
source3/smbd/nttrans.c
source3/smbd/open.c
source3/smbd/posix_acls.c
source3/smbd/process.c
source3/smbd/reply.c
source3/smbd/server.c
source3/utils/net_ads.c
source3/utils/net_dns.c
source3/utils/net_proto.h
source3/utils/net_rap.c
source3/utils/net_rpc.c
source3/utils/net_util.c
source3/utils/sharesec.c
source3/utils/smbcacls.c
source3/utils/testparm.c
source3/web/statuspage.c
source3/winbindd/idmap_adex/domain_util.c
source3/winbindd/idmap_adex/likewise_cell.c
source3/winbindd/idmap_tdb2.c
source3/winbindd/idmap_util.c
source3/winbindd/winbindd_dual.c
source3/winbindd/winbindd_locator.c
source3/winbindd/winbindd_util.c
source4/BUGS [moved from BUGS4.txt with 100% similarity]
source4/Makefile
source4/NEWS [moved from NEWS4 with 100% similarity]
source4/TODO [moved from TODO4 with 98% similarity]
source4/auth/gensec/cyrus_sasl.c
source4/auth/gensec/gensec.c
source4/auth/gensec/gensec.h
source4/auth/gensec/schannel_state.c
source4/auth/gensec/spnego.c
source4/auth/kerberos/kerberos.c
source4/auth/kerberos/kerberos_util.c
source4/auth/kerberos/krb5_init_context.c
source4/auth/ntlm/auth_server.c
source4/autogen.sh
source4/build/m4/check_path.m4
source4/cldap_server/cldap_server.c
source4/cldap_server/netlogon.c
source4/cldap_server/rootdse.c
source4/client/cifsdd.c
source4/client/cifsdd.h
source4/client/cifsddio.c
source4/client/client.c
source4/client/smbmount.c
source4/configure.ac
source4/dsdb/samdb/cracknames.c
source4/dsdb/samdb/ldb_modules/anr.c
source4/dsdb/samdb/ldb_modules/extended_dn.c
source4/dsdb/samdb/ldb_modules/instancetype.c
source4/dsdb/samdb/ldb_modules/kludge_acl.c
source4/dsdb/samdb/ldb_modules/linked_attributes.c
source4/dsdb/samdb/ldb_modules/local_password.c
source4/dsdb/samdb/ldb_modules/normalise.c
source4/dsdb/samdb/ldb_modules/objectclass.c
source4/dsdb/samdb/ldb_modules/objectguid.c
source4/dsdb/samdb/ldb_modules/partition.c
source4/dsdb/samdb/ldb_modules/password_hash.c
source4/dsdb/samdb/ldb_modules/proxy.c
source4/dsdb/samdb/ldb_modules/ranged_results.c
source4/dsdb/samdb/ldb_modules/repl_meta_data.c
source4/dsdb/samdb/ldb_modules/rootdse.c
source4/dsdb/samdb/ldb_modules/samldb.c
source4/dsdb/samdb/ldb_modules/schema_fsmo.c
source4/dsdb/samdb/ldb_modules/show_deleted.c
source4/dsdb/samdb/ldb_modules/simple_ldap_map.c
source4/dsdb/samdb/ldb_modules/subtree_delete.c
source4/dsdb/samdb/ldb_modules/subtree_rename.c
source4/dsdb/samdb/ldb_modules/tests/samba3sam.py
source4/dsdb/samdb/ldb_modules/update_keytab.c
source4/dsdb/samdb/samdb.h
source4/dsdb/schema/schema_description.c
source4/dynconfig/config.mk
source4/dynconfig/dynconfig.c
source4/heimdal/kdc/krb5tgs.c
source4/heimdal/lib/hdb/hdb.c
source4/heimdal/lib/hdb/hdb.h
source4/kdc/config.mk
source4/kdc/hdb-samba4.c [moved from source4/kdc/hdb-ldb.c with 95% similarity]
source4/kdc/kdc.c
source4/ldap_server/ldap_backend.c
source4/lib/charset/util_unistr.c
source4/lib/ldb/common/ldb.c
source4/lib/ldb/common/ldb_dn.c
source4/lib/ldb/common/ldb_modules.c
source4/lib/ldb/include/ldb.h
source4/lib/ldb/include/ldb_private.h
source4/lib/ldb/ldb.i
source4/lib/ldb/ldb_ildap/ldb_ildap.c
source4/lib/ldb/ldb_ldap/ldb_ldap.c
source4/lib/ldb/ldb_map/ldb_map.c
source4/lib/ldb/ldb_map/ldb_map.h
source4/lib/ldb/ldb_map/ldb_map_inbound.c
source4/lib/ldb/ldb_map/ldb_map_outbound.c
source4/lib/ldb/ldb_map/ldb_map_private.h
source4/lib/ldb/ldb_sqlite3/ldb_sqlite3.c
source4/lib/ldb/ldb_tdb/ldb_index.c
source4/lib/ldb/ldb_tdb/ldb_search.c
source4/lib/ldb/ldb_tdb/ldb_tdb.c
source4/lib/ldb/ldb_tdb/ldb_tdb.h
source4/lib/ldb/ldb_wrap.c
source4/lib/ldb/libldb.m4
source4/lib/ldb/modules/asq.c
source4/lib/ldb/modules/operational.c
source4/lib/ldb/modules/paged_results.c
source4/lib/ldb/modules/paged_searches.c
source4/lib/ldb/modules/rdn_name.c
source4/lib/ldb/modules/sort.c
source4/lib/ldb/tests/python/ldap.py
source4/lib/ldb/tools/ldbsearch.c
source4/lib/ldb_wrap.c
source4/lib/registry/patchfile.c
source4/lib/registry/tests/generic.c
source4/lib/util/idtree.c
source4/lib/wmi/wmi.h
source4/lib/wmi/wmicore.c
source4/libcli/cliconnect.c
source4/libcli/clideltree.c
source4/libcli/config.mk
source4/libcli/drsblobs.h [deleted file]
source4/libcli/ldap/ldap_client.c
source4/libcli/nbt/man/nmblookup.1.xml [new file with mode: 0644]
source4/libcli/nbt/tools/nmblookup.c [moved from source4/utils/nmblookup.c with 100% similarity]
source4/libcli/raw/clisession.c
source4/libcli/raw/clitree.c
source4/libcli/raw/interfaces.h
source4/libcli/resolve/bcast.c
source4/libcli/resolve/resolve.c
source4/libcli/security/security.i
source4/libcli/security/security.py
source4/libcli/security/security_wrap.c
source4/libcli/smb2/connect.c
source4/libcli/smb2/request.c
source4/libcli/smb2/smb2.h
source4/libcli/smb2/util.c
source4/libcli/smb_composite/connect.c
source4/libcli/smb_composite/fetchfile.c
source4/libcli/smb_composite/fsinfo.c
source4/libcli/smb_composite/smb_composite.h
source4/libnet/libnet_become_dc.c
source4/libnet/libnet_samdump_keytab.c
source4/libnet/libnet_site.c
source4/libnet/libnet_unbecome_dc.c
source4/librpc/config.mk
source4/librpc/idl/dcerpc.idl
source4/librpc/idl/drsblobs.idl
source4/librpc/idl/drsuapi.idl
source4/librpc/idl/lsa.idl
source4/librpc/idl/misc.idl
source4/librpc/idl/netlogon.idl
source4/librpc/idl/security.idl
source4/librpc/ndr/ndr_drsblobs.c [moved from source4/libcli/drsblobs.c with 82% similarity]
source4/librpc/rpc/dcerpc.c
source4/librpc/rpc/dcerpc_connect.c
source4/librpc/rpc/dcerpc_secondary.c
source4/librpc/rpc/dcerpc_sock.c
source4/nbt_server/dgram/netlogon.c
source4/nbt_server/irpc.c
source4/ntvfs/cifs/vfs_cifs.c
source4/ntvfs/posix/pvfs_acl.c
source4/param/loadparm.c
source4/param/param.h
source4/rpc_server/dcerpc_server.c
source4/rpc_server/dcesrv_auth.c
source4/rpc_server/handles.c
source4/rpc_server/lsa/dcesrv_lsa.c
source4/rpc_server/lsa/lsa_init.c
source4/rpc_server/lsa/lsa_lookup.c
source4/rpc_server/netlogon/dcerpc_netlogon.c
source4/rpc_server/service_rpc.c
source4/samba4-skip
source4/script/installlib.sh
source4/script/installmisc.sh
source4/script/uninstallheader.sh [deleted file]
source4/scripting/bin/minschema
source4/scripting/bin/subunitrun
source4/scripting/python/config.mk
source4/scripting/python/samba/provision.py
source4/scripting/python/samba/tests/dcerpc/rpcecho.py
source4/selftest/config.mk
source4/selftest/samba4_tests.sh
source4/setup/provision_basedn_modify.ldif
source4/setup/provision_users.ldif
source4/setup/schema_samba4.ldif
source4/setup/secrets_dc.ldif
source4/smb_server/blob.c
source4/smb_server/config.mk
source4/smb_server/smb/request.c
source4/smb_server/smb2/fileinfo.c
source4/smb_server/smb2/fileio.c
source4/smb_server/smb2/keepalive.c
source4/smb_server/smb2/negprot.c
source4/smb_server/smb2/receive.c
source4/smb_server/smb2/smb2_server.h
source4/smb_server/smb_samba3.c
source4/smb_server/smb_server.h
source4/smbd/process_model.h
source4/smbd/process_prefork.c
source4/smbd/process_single.c
source4/smbd/process_standard.c
source4/smbd/process_thread.c
source4/smbd/service_stream.c
source4/smbd/service_task.c
source4/torture/basic/misc.c
source4/torture/basic/secleak.c
source4/torture/config.mk
source4/torture/gentest.c
source4/torture/ldap/cldap.c
source4/torture/ldap/schema.c
source4/torture/locktest.c
source4/torture/locktest2.c
source4/torture/masktest.c
source4/torture/nbt/dgram.c
source4/torture/ndr/lsa.c
source4/torture/raw/chkpath.c
source4/torture/raw/composite.c
source4/torture/raw/context.c
source4/torture/raw/lock.c
source4/torture/raw/lockbench.c
source4/torture/raw/notify.c
source4/torture/raw/open.c
source4/torture/raw/openbench.c
source4/torture/raw/oplock.c
source4/torture/raw/tconrate.c
source4/torture/rpc/drsuapi_cracknames.c
source4/torture/rpc/dssync.c
source4/torture/rpc/join.c
source4/torture/rpc/lsa.c
source4/torture/rpc/netlogon.c
source4/torture/rpc/object_uuid.c [new file with mode: 0644]
source4/torture/rpc/rpc.c
source4/torture/rpc/samba3rpc.c
source4/torture/rpc/samlogon.c
source4/torture/rpc/testjoin.c
source4/torture/smb2/create.c
source4/torture/unix/unix_info2.c
source4/torture/unix/whoami.c
source4/torture/util_smb.c
source4/utils/ad2oLschema.c
source4/utils/config.mk
source4/utils/man/ndrdump.1.xml [deleted file]
testprogs/blackbox/test_ldb.sh

index b87f786678e7ac0496a7975063141b2985213415..e585504ce5e3c575a804d4a0725f5864226342c6 100644 (file)
@@ -252,10 +252,10 @@ source4/param/proto.h
 source4/param/secrets_proto.h
 source4/param/share_proto.h
 source4/passdb/proto.h
-source4/pidl/blib
-source4/pidl/cover_db
-source4/pidl/Makefile
-source4/pidl/pm_to_blib
+pidl/blib
+pidl/cover_db
+pidl/Makefile
+pidl/pm_to_blib
 source4/rpc_server/common/proto.h
 source4/rpc_server/dcerpc_server_proto.h
 source4/rpc_server/lsa/proto.h
index 8063ae8691a78996e372bb068abe17a3bce0f51e..c1b6641a5aebf7de4d5e85d28cfd10403599e53c 100644 (file)
@@ -1,6 +1,7 @@
-##
-## Coding conventions in the Samba 3 tree
-##
+Coding conventions in the Samba tree
+------------------------------------
+
+.. contents::
 
 ===========
 Quick Start
@@ -14,15 +15,13 @@ style should never outweigh coding itself and so the the guidelines
 described here are hopefully easy enough to follow as they are very
 common and supported by tools and editors.
 
-The basic style, also mentioned in the SAMBA_4_0/prog_guide.txt is the
-Linux kernel coding style (See Documentation/CodingStyle in the kernel
-source tree).  The closely matches what most Samba developers use already
-anyways.
+The basic style, also mentioned in prog_guide4.txt, is the Linux kernel coding 
+style (See Documentation/CodingStyle in the kernel source tree). This closely 
+matches what most Samba developers use already anyways.
 
 But to save you the trouble of reading the Linux kernel style guide, here
 are the highlights.
 
-
 * Maximum Line Width is 80 Characters
   The reason is not for people with low-res screens but rather sticking
   to 80 columns prevents you from easily nesting more than one level of
@@ -59,14 +58,14 @@ Vi
 --
 (Thanks to SATOH Fumiyasu <fumiyas@osstech.jp> for these hints):
 
-For the basic vi editor including with all variants of *nix, add the 
+For the basic vi editor including with all variants of \*nix, add the 
 following to $HOME/.exrc:
 
   set tabstop=8
   set shiftwidth=8
 
 For Vim, the following settings in $HOME/.vimrc will also deal with 
-displaying trailing whitespace:
+displaying trailing whitespace::
 
   if has("syntax") && (&t_Co > 2 || has("gui_running"))
        syntax on
@@ -91,7 +90,7 @@ FAQ & Statement Reference
 Comments
 --------
 
-Comments should always use the standard C syntax.  I.e. /* ... */.  C++ 
+Comments should always use the standard C syntax.  C++ 
 style comments are not currently allowed.
 
 
@@ -145,7 +144,7 @@ The exception to the ending rule is when the closing brace is followed by
 another language keyword such as else or the closing while in a do..while 
 loop.
 
-Good examples:
+Good examples::
 
        if (x == 1) {
                printf("good\n");
@@ -162,7 +161,7 @@ Good examples:
                printf("also good\n");
        } while (1);
 
-Bad examples:
+Bad examples::
 
        while (1)
        {
@@ -177,29 +176,29 @@ evil, they can greatly enhance readability and reduce memory leaks when used
 as the single exit point from a function.  But in no Samba world what so ever 
 is a goto outside of a function or block of code a good idea.
 
-Good Examples:
-
-int function foo(int y)
-{
-       int *z = NULL;
-       int ret = 0;
+Good Examples::
 
-       if ( y < 10 ) {
-               z = malloc(sizeof(int)*y);
-               if (!z) {
-                       ret = 1;
-                       goto done;
+       int function foo(int y)
+       {
+               int *z = NULL;
+               int ret = 0;
+
+               if ( y < 10 ) {
+                       z = malloc(sizeof(int)*y);
+                       if (!z) {
+                               ret = 1;
+                               goto done;
+                       }
                }
-       }
 
-       print("Allocated %d elements.\n", y);
+               print("Allocated %d elements.\n", y);
 
- done: 
-       if (z)
-               free(z);
       done: 
+               if (z)
+                       free(z);
 
-       return ret;
-}
+               return ret;
+       }
 
 
 Checking Pointer Values
@@ -207,13 +206,13 @@ Checking Pointer Values
 
 When invoking functions that return pointer values, either of the following 
 are acceptable.  Use you best judgement and choose the more readable option.
-Remember that many other people will review it.
+Remember that many other people will review it.::
 
        if ((x = malloc(sizeof(short)*10)) == NULL ) {
                fprintf(stderr, "Unable to alloc memory!\n");
        }
 
-or
+or::
 
        x = malloc(sizeof(short)*10);
        if (!x) {
diff --git a/docs-xml/manpages-3/idmap_adex.8.xml b/docs-xml/manpages-3/idmap_adex.8.xml
new file mode 100644 (file)
index 0000000..9eb2ff7
--- /dev/null
@@ -0,0 +1,89 @@
+<?xml version="1.0" encoding="iso-8859-1"?>
+<!DOCTYPE refentry PUBLIC "-//Samba-Team//DTD DocBook V4.2-Based Variant V1.0//EN" "http://www.samba.org/samba/DTD/samba-doc">
+<refentry id="idmap_adex.8">
+
+<refmeta>
+       <refentrytitle>idmap_adex</refentrytitle>
+       <manvolnum>8</manvolnum>
+       <refmiscinfo class="source">Samba</refmiscinfo>
+       <refmiscinfo class="manual">System Administration tools</refmiscinfo>
+       <refmiscinfo class="version">3.2</refmiscinfo>
+</refmeta>
+
+
+<refnamediv>
+       <refname>idmap_adex</refname>
+       <refpurpose>Samba's idmap_adex Backend for Winbind</refpurpose>
+</refnamediv>
+
+<refsynopsisdiv>
+       <title>DESCRIPTION</title>
+       <para>
+         The idmap_adex plugin provides a way for Winbind to read
+         id mappings from an AD server that uses RFC2307 schema
+         extensions. This module implements both the idmap and nss_info
+         APIs and supports domain trustes as well as two-way cross
+         forest trusts.  It is a read-only plugin requiring that the
+         administrator provide mappings in advance by adding the
+         POSIX attribute information to the users and groups objects
+         in AD.  The most common means of doing this is using &quot;Identity
+         Services for Unix&quot; support on Windows 2003 R2 and later.
+       </para>
+
+       <para>
+         Note that you must add the uidNumber, gidNumber, and uid
+         attributes to the partial attribute set of the forest global
+         catalog servers.  This can be done using the Active Directory Schema
+         Management MMC plugin (schmmgmt.dll).
+       </para>
+</refsynopsisdiv>
+
+<refsynopsisdiv>
+       <title>NSS_INFO</title>
+       <para>
+         The nss_info plugin supports reading the unixHomeDirectory,
+         gidNumber, loginShell, and uidNumber attributes from the user
+         object and the gidNumber attribute from the group object to
+         fill in information required by the libc getpwnam() and
+         getgrnam() family of functions.  Group membership is filled in
+         according to the Windows group membership and not the
+         msSFU30PosixMember attribute.
+       </para>
+
+       <para>
+         Username aliases are implement by setting the uid attribute
+         on the user object.  While group name aliases are implemented
+         by reading the displayname attribute from the group object.
+       </para>
+</refsynopsisdiv>
+
+<refsect1>
+       <title>EXAMPLES</title>
+       <para>
+         The following example shows how to retrieve idmappings and NSS data
+         from our principal and trusted AD domains.
+       </para>
+
+       <programlisting>
+       [global]
+       idmap backend = adex
+       idmap uid = 1000-4000000000
+       idmap gid = 1000-4000000000
+
+       winbind nss info = adex
+       winbind normalize names = yes
+       </programlisting>
+</refsect1>
+
+<refsect1>
+       <title>AUTHOR</title>
+
+       <para>
+       The original Samba software and related utilities
+       were created by Andrew Tridgell. Samba is now developed
+       by the Samba Team as an Open Source project similar
+       to the way the Linux kernel is developed.
+       </para>
+</refsect1>
+
+</refentry>
diff --git a/docs-xml/manpages-3/idmap_hash.8.xml b/docs-xml/manpages-3/idmap_hash.8.xml
new file mode 100644 (file)
index 0000000..8e452b3
--- /dev/null
@@ -0,0 +1,76 @@
+<?xml version="1.0" encoding="iso-8859-1"?>
+<!DOCTYPE refentry PUBLIC "-//Samba-Team//DTD DocBook V4.2-Based Variant V1.0//EN" "http://www.samba.org/samba/DTD/samba-doc">
+<refentry id="idmap_hash.8">
+
+<refmeta>
+       <refentrytitle>idmap_hash</refentrytitle>
+       <manvolnum>8</manvolnum>
+       <refmiscinfo class="source">Samba</refmiscinfo>
+       <refmiscinfo class="manual">System Administration tools</refmiscinfo>
+       <refmiscinfo class="version">3.2</refmiscinfo>
+</refmeta>
+
+
+<refnamediv>
+       <refname>idmap_hash</refname>
+       <refpurpose>Samba's idmap_hash Backend for Winbind</refpurpose>
+</refnamediv>
+
+<refsynopsisdiv>
+       <title>DESCRIPTION</title>
+       <para>The idmap_hash plugin implements a hashing algorithm used
+         map SIDs for domain users and groups to a 31-bit uid and gid.
+         This plugin also implements the nss_info API and can be used
+         to support a local name mapping files if enabled via the
+         &quot;winbind normlaize names&quot; and &quot;winbind nss info&quot;
+         parameters in smb.conf.
+       </para>
+</refsynopsisdiv>
+
+<refsect1>
+       <title>IDMAP OPTIONS</title>
+
+       <variablelist>
+               <varlistentry>
+               <term>name_map</term>
+               <listitem><para>
+                   Specifies the absolute path to the name mapping
+                   file used by the nss_info API.  Entries in the file
+                   are of the form &quot;<replaceable>unix name</replaceable>
+                   = <replaceable>qualified domain name</replaceable>&quote;.
+                   Mapping of both user and group names is supported.
+               </para></listitem>
+               </varlistentry>
+       </variablelist>
+</refsect1>
+
+<refsect1>
+       <title>EXAMPLES</title>
+       <para>The following example utilizes the idmap_hash plugin for
+         the idmap and nss_info information.
+       </para>
+
+       <programlisting>
+       [global]
+       idmap backend = hash
+       idmap uid = 1000-4000000000
+       idmap gid = 1000-4000000000
+
+       winbind nss info = hash
+       winbind normalize names = yes
+       idmap_hash:name_map = /etc/samba/name_map.cfg
+       </programlisting>
+</refsect1>
+
+<refsect1>
+       <title>AUTHOR</title>
+
+       <para>
+       The original Samba software and related utilities
+       were created by Andrew Tridgell. Samba is now developed
+       by the Samba Team as an Open Source project similar
+       to the way the Linux kernel is developed.
+       </para>
+</refsect1>
+
+</refentry>
index cf7fd5a0f63d149900175568349bf45c3e725bf9..7f233c13862c79b65b2a02810a4338311d283e8f 100644 (file)
                </para></listitem>
                </varlistentry>
 
+               <varlistentry>
+               <term>mkhomedir</term>
+               <listitem><para>
+               Create homedirectory for a user on-the-fly, option is valid in
+               PAM session block.
+               </para></listitem>
+               </varlistentry>
+
                </variablelist>
 
 
diff --git a/docs-xml/manpages-3/vfs_smb_traffic_analyzer.8.xml b/docs-xml/manpages-3/vfs_smb_traffic_analyzer.8.xml
new file mode 100644 (file)
index 0000000..28c8413
--- /dev/null
@@ -0,0 +1,157 @@
+<?xml version="1.0" encoding="iso-8859-1"?>
+<!DOCTYPE refentry PUBLIC "-//Samba-Team//DTD DocBook V4.2-Based Variant V1.0//EN" "http://www.samba.org/samba/DTD/samba-doc">
+<refentry id="vfs_smb_traffic_analyzer.8">
+
+<refmeta>
+       <refentrytitle>smb_traffic_analyzer</refentrytitle>
+       <manvolnum>8</manvolnum>
+       <refmiscinfo class="source">Samba</refmiscinfo>
+       <refmiscinfo class="manual">System Administration tools</refmiscinfo>
+       <refmiscinfo class="version">3.3</refmiscinfo>
+</refmeta>
+
+
+<refnamediv>
+       <refname>vfs_smb_traffic_analyzer</refname>
+       <refpurpose>log Samba VFS read and write operations through a socket
+       to a helper application</refpurpose>
+</refnamediv>
+
+<refsynopsisdiv>
+       <cmdsynopsis>
+               <command>vfs objects = smb_traffic_analyzer</command>
+       </cmdsynopsis>
+</refsynopsisdiv>
+
+<refsect1>
+       <title>DESCRIPTION</title>
+
+       <para>This VFS module is part of the
+       <citerefentry><refentrytitle>samba</refentrytitle>
+       <manvolnum>7</manvolnum></citerefentry> suite.</para>
+
+       <para>The <command>vfs_smb_traffic_analyzer</command> VFS module logs
+       client write and read operations on a Samba server and sends this data
+       over a socket to a helper program, which feeds a SQL database. More
+       information on the helper programs can be obtained from the
+       homepage of the project at:
+       http://holger123.wordpress.com/smb-traffic-analyzer/
+       </para>
+       <para><command>vfs_smb_traffic_analyzer</command> currently is aware
+       of the following VFS operations:</para>
+
+       <simplelist>
+        <member>write</member>
+        <member>pwrite</member>
+       <member>read</member>
+       <member>pread</member>
+       </simplelist>
+
+       <para><command>vfs_smb_traffic_analyzer</command> sends the following data
+       in a fixed format seperated by a comma through either an internet or a
+       unix domain socket:</para>
+       <programlisting>
+       BYTES|USER|DOMAIN|READ/WRITE|SHARE|FILENAME|TIMESTAMP
+       </programlisting>
+
+       <para>Description of the records:
+
+       <itemizedlist>
+       <listitem><para><command>BYTES</command> - the length in bytes of the VFS operation</para></listitem>
+       <listitem><para><command>USER</command> - the user who initiated the operation</para></listitem>
+       <listitem><para><command>DOMAIN</command> - the domain of the user</para></listitem>
+       <listitem><para><command>READ/WRITE</command> - either "W" for a write operation or "R" for read</para></listitem>
+       <listitem><para><command>SHARE</command> - the name of the share on which the VFS operation occured</para></listitem>
+       <listitem><para><command>FILENAME</command> - the name of the file that was used by the VFS operation</para></listitem>
+       <listitem><para><command>TIMESTAMP</command> - a timestamp, formatted as "yyyy-mm-dd hh-mm-ss.ms" indicating when the VFS operation occured</para></listitem>
+       </itemizedlist>
+
+       </para>
+
+       <para>This module is stackable.</para>
+
+</refsect1>
+
+
+<refsect1>
+       <title>OPTIONS</title>
+
+       <variablelist>
+
+               <varlistentry>
+                <term>smb_traffic_analyzer:mode = STRING</term>
+                <listitem>
+                <para>If STRING matches to "unix_domain_socket", the module will
+               use a unix domain socket located at /var/tmp/stadsocket, if
+               STRING contains an different string or is not defined, the module will
+               use an internet domain socket for data transfer.</para>
+
+                </listitem>
+                </varlistentry>
+
+
+               <varlistentry>
+               <term>smb_traffic_analyzer:host = STRING</term>
+               <listitem>
+               <para>The module will send the data to the system named with
+               the hostname STRING.</para>
+
+               </listitem>
+               </varlistentry>
+
+               <varlistentry>
+               <term>smb_traffic_analyzer:port = STRING</term>
+               <listitem>
+               <para>The module will send the data using the TCP port given
+               in STRING
+               </para>
+
+               </listitem>
+               </varlistentry>
+
+
+       </variablelist>
+</refsect1>
+
+<refsect1>
+       <title>EXAMPLES</title>
+
+       <para>The module running on share "example_share", using a unix domain socket</para>
+       <programlisting>
+       <smbconfsection name="[example_share]"/>
+       <smbconfoption name="path">/data/example</smbconfoption>
+       <smbconfoption name="vfs objects">smb_traffic_analyzer</smbconfoption>
+       <smbconfoption name="smb_traffic_analyzer:mode">unix_domain_socket</smbconfoption>
+       </programlisting>
+
+       <para>The module running on share "example_share", using an internet domain socket,
+       connecting to host "examplehost" on port 3491.</para>
+       <programlisting>
+       <smbconfsection name="[example_share]"/>
+       <smbconfoption name="path">/data/example</smbconfoption>
+       <smbconfoption name="vfs objects">smb_traffic_analyzer</smbconfoption>
+       <smbconfoption name="smb_traffic_analyzer:host">examplehost</smbconfoption>
+       <smbconfoption name="smb_traffic_analyzer:port">3490</smbconfoption>
+       </programlisting>
+
+</refsect1>
+
+<refsect1>
+       <title>VERSION</title>
+       <para>This man page is correct for version 3.3 of the Samba suite.
+       </para>
+</refsect1>
+
+<refsect1>
+       <title>AUTHOR</title>
+
+       <para>The original Samba software and related utilities
+       were created by Andrew Tridgell. Samba is now developed
+       by the Samba Team as an Open Source project similar
+       to the way the Linux kernel is developed.</para>
+
+       <para>The original version of the VFS module and the
+       helper tools were created by Holger Hetterich.</para>
+</refsect1>
+
+</refentry>
diff --git a/docs-xml/smbdotconf/printing/cupsconnectiontimeout.xml b/docs-xml/smbdotconf/printing/cupsconnectiontimeout.xml
new file mode 100644 (file)
index 0000000..1c7df15
--- /dev/null
@@ -0,0 +1,20 @@
+<samba:parameter name="cups connection timeout"
+                 context="G"
+                type="integer"
+                print="1"
+                 xmlns:samba="http://www.samba.org/samba/DTD/samba-doc">
+<description>
+    <para>
+    This parameter is only applicable if <smbconfoption name="printing"/> is set to <constant>cups</constant>.
+    </para>
+
+   <para>
+   If set, this option specifies the number of seconds that smbd will wait
+   whilst trying to contact to the CUPS server. The connection will fail
+   if it takes longer than this number of seconds.
+   </para>
+</description>
+
+<value type="default">30</value>
+<value type="example">60</value>
+</samba:parameter>
diff --git a/docs-xml/smbdotconf/printing/cupstimeout.xml b/docs-xml/smbdotconf/printing/cupstimeout.xml
deleted file mode 100644 (file)
index 727ccce..0000000
+++ /dev/null
@@ -1,17 +0,0 @@
-<samba:parameter name="cups timeout"
-                 context="G"
-                type="integer"
-                print="1"
-                advanced="1"
-                 xmlns:samba="http://www.samba.org/samba/DTD/samba-doc">
-
-<description>
-    <para>
-    This parameter determines the timeout for connections to a CUPS server
-    in seconds.
-    </para>
-</description>
-
-<value type="default">30</value>
-<value type="example">cups timeout = 10</value>
-</samba:parameter>
index 28826cf5f36260695f822e81f1973f25c0a933b9..5b68bca9124b9ba4959d0376137d9a50272ab206 100644 (file)
@@ -5,14 +5,25 @@
                  xmlns:samba="http://www.samba.org/samba/DTD/samba-doc">
 <description>
        <para>This parameter controls whether winbindd will replace
-       whitespace in user and group names with an underscore (_) character.
-       For example, whether the name &quot;Space Kadet&quot; should be
-       replaced with the string &quot;space_kadet&quot;.
-       Frequently Unix shell scripts will have difficulty with usernames 
-       contains whitespace due to the default field separator in the shell.
-       Do not enable this option if the underscore character is used in
-       account names within your domain
-       </para>
+         whitespace in user and group names with an underscore (_) character.
+         For example, whether the name &quot;Space Kadet&quot; should be
+         replaced with the string &quot;space_kadet&quot;.
+         Frequently Unix shell scripts will have difficulty with usernames
+         contains whitespace due to the default field separator in the shell.
+         If your domain possesses names containing the underscore character,
+         this option may cause problems unless the name aliasing feature
+         is supported by your nss_info plugin.
+        </para>
+
+       <para>This feature also enables the name aliasing API which can
+         be used to make domain user and group names to a non-qlaified
+         version.  Please refer to the manpage for the configured
+         idmap and nss_info plugin for the specifics on how to configure
+         name aliasing for a specific configuration.  Name aliasing takes
+         precendence (and is mutually exclusive) over the whitespace
+         replacement mechanism discussed previsouly.
+         </para>
+
 </description>
 
 <value type="default">no</value>
index 89d8ce5239a68a388607334ea2086dc930e5caf6..3df1fcd5bfb98d9c87191967e5824361a9d87eb3 100644 (file)
@@ -315,7 +315,7 @@ static size_t skel_get_nt_acl(vfs_handle_struct *handle,
 }
 
 static NTSTATUS skel_fset_nt_acl(vfs_handle_struct *handle, files_struct *fsp,
-       uint32 security_info_sent, SEC_DESC *psd)
+       uint32 security_info_sent, const SEC_DESC *psd)
 {
        errno = ENOSYS;
        return NT_STATUS_NOT_IMPLEMENTED;
index ea8530d855effd1ba701a5e749dfd93f338f50a9..e6dee97775b92070b19dedd2a144e6d154450e10 100644 (file)
@@ -302,7 +302,7 @@ static NTSTATUS skel_get_nt_acl(vfs_handle_struct *handle,
 }
 
 static NTSTATUS skel_fset_nt_acl(vfs_handle_struct *handle, files_struct *fsp,
-       uint32 security_info_sent, SEC_DESC *psd)
+       uint32 security_info_sent, const SEC_DESC *psd)
 {
        return SMB_VFS_NEXT_FSET_NT_ACL(handle, fsp, security_info_sent, psd);
 }
index a9e02a833a526f647ce7838a44e08a3ef5bd2dad..dd0b112f30424e8df3e956d9f9d6defd5a9435c2 100644 (file)
@@ -33,3 +33,6 @@
 
 # omit pam conversations
 ;silent = no
+
+# create homedirectory on the fly
+;mkhomedir = no
index e8d27adc37fd8487a128c675aff582e009cc11c7..9d619769507792cef1984f36b20e67539180dd93 100644 (file)
@@ -750,7 +750,7 @@ static struct swrap_packet *swrap_packet_init(struct timeval *tval,
                                              int socket_type,
                                              const unsigned char *payload,
                                              size_t payload_len,
-                                             unsigned long tcp_seq,
+                                             unsigned long tcp_seqno,
                                              unsigned long tcp_ack,
                                              unsigned char tcp_ctl,
                                              int unreachable,
@@ -852,7 +852,7 @@ static struct swrap_packet *swrap_packet_init(struct timeval *tval,
        case SOCK_STREAM:
                packet->ip.p.tcp.source_port    = src_port;
                packet->ip.p.tcp.dest_port      = dest_port;
-               packet->ip.p.tcp.seq_num        = htonl(tcp_seq);
+               packet->ip.p.tcp.seq_num        = htonl(tcp_seqno);
                packet->ip.p.tcp.ack_num        = htonl(tcp_ack);
                packet->ip.p.tcp.hdr_length     = 0x50; /* 5 * 32 bit words */
                packet->ip.p.tcp.control        = tcp_ctl;
@@ -916,7 +916,7 @@ static struct swrap_packet *swrap_marshall_packet(struct socket_info *si,
 {
        const struct sockaddr_in *src_addr;
        const struct sockaddr_in *dest_addr;
-       unsigned long tcp_seq = 0;
+       unsigned long tcp_seqno = 0;
        unsigned long tcp_ack = 0;
        unsigned char tcp_ctl = 0;
        int unreachable = 0;
@@ -937,7 +937,7 @@ static struct swrap_packet *swrap_marshall_packet(struct socket_info *si,
                src_addr = (const struct sockaddr_in *)si->myname;
                dest_addr = (const struct sockaddr_in *)addr;
 
-               tcp_seq = si->io.pck_snd;
+               tcp_seqno = si->io.pck_snd;
                tcp_ack = si->io.pck_rcv;
                tcp_ctl = 0x02; /* SYN */
 
@@ -951,7 +951,7 @@ static struct swrap_packet *swrap_marshall_packet(struct socket_info *si,
                dest_addr = (const struct sockaddr_in *)si->myname;
                src_addr = (const struct sockaddr_in *)addr;
 
-               tcp_seq = si->io.pck_rcv;
+               tcp_seqno = si->io.pck_rcv;
                tcp_ack = si->io.pck_snd;
                tcp_ctl = 0x12; /** SYN,ACK */
 
@@ -966,7 +966,7 @@ static struct swrap_packet *swrap_marshall_packet(struct socket_info *si,
                src_addr = (const struct sockaddr_in *)addr;
 
                /* Unreachable: resend the data of SWRAP_CONNECT_SEND */
-               tcp_seq = si->io.pck_snd - 1;
+               tcp_seqno = si->io.pck_snd - 1;
                tcp_ack = si->io.pck_rcv;
                tcp_ctl = 0x02; /* SYN */
                unreachable = 1;
@@ -979,7 +979,7 @@ static struct swrap_packet *swrap_marshall_packet(struct socket_info *si,
                src_addr = (const struct sockaddr_in *)si->myname;
                dest_addr = (const struct sockaddr_in *)addr;
 
-               tcp_seq = si->io.pck_snd;
+               tcp_seqno = si->io.pck_snd;
                tcp_ack = si->io.pck_rcv;
                tcp_ctl = 0x10; /* ACK */
 
@@ -991,7 +991,7 @@ static struct swrap_packet *swrap_marshall_packet(struct socket_info *si,
                dest_addr = (const struct sockaddr_in *)si->myname;
                src_addr = (const struct sockaddr_in *)addr;
 
-               tcp_seq = si->io.pck_rcv;
+               tcp_seqno = si->io.pck_rcv;
                tcp_ack = si->io.pck_snd;
                tcp_ctl = 0x02; /* SYN */
 
@@ -1005,7 +1005,7 @@ static struct swrap_packet *swrap_marshall_packet(struct socket_info *si,
                src_addr = (const struct sockaddr_in *)si->myname;
                dest_addr = (const struct sockaddr_in *)addr;
 
-               tcp_seq = si->io.pck_snd;
+               tcp_seqno = si->io.pck_snd;
                tcp_ack = si->io.pck_rcv;
                tcp_ctl = 0x12; /* SYN,ACK */
 
@@ -1019,7 +1019,7 @@ static struct swrap_packet *swrap_marshall_packet(struct socket_info *si,
                dest_addr = (const struct sockaddr_in *)si->myname;
                src_addr = (const struct sockaddr_in *)addr;
 
-               tcp_seq = si->io.pck_rcv;
+               tcp_seqno = si->io.pck_rcv;
                tcp_ack = si->io.pck_snd;
                tcp_ctl = 0x10; /* ACK */
 
@@ -1029,7 +1029,7 @@ static struct swrap_packet *swrap_marshall_packet(struct socket_info *si,
                src_addr = (const struct sockaddr_in *)si->myname;
                dest_addr = (const struct sockaddr_in *)si->peername;
 
-               tcp_seq = si->io.pck_snd;
+               tcp_seqno = si->io.pck_snd;
                tcp_ack = si->io.pck_rcv;
                tcp_ctl = 0x18; /* PSH,ACK */
 
@@ -1047,7 +1047,7 @@ static struct swrap_packet *swrap_marshall_packet(struct socket_info *si,
                                          buf, len, packet_len);
                }
 
-               tcp_seq = si->io.pck_rcv;
+               tcp_seqno = si->io.pck_rcv;
                tcp_ack = si->io.pck_snd;
                tcp_ctl = 0x14; /** RST,ACK */
 
@@ -1061,7 +1061,7 @@ static struct swrap_packet *swrap_marshall_packet(struct socket_info *si,
                        return NULL;
                }
 
-               tcp_seq = si->io.pck_rcv;
+               tcp_seqno = si->io.pck_rcv;
                tcp_ack = si->io.pck_snd;
                tcp_ctl = 0x14; /* RST,ACK */
 
@@ -1071,7 +1071,7 @@ static struct swrap_packet *swrap_marshall_packet(struct socket_info *si,
                dest_addr = (const struct sockaddr_in *)si->myname;
                src_addr = (const struct sockaddr_in *)si->peername;
 
-               tcp_seq = si->io.pck_rcv;
+               tcp_seqno = si->io.pck_rcv;
                tcp_ack = si->io.pck_snd;
                tcp_ctl = 0x18; /* PSH,ACK */
 
@@ -1087,7 +1087,7 @@ static struct swrap_packet *swrap_marshall_packet(struct socket_info *si,
                        return NULL;
                }
 
-               tcp_seq = si->io.pck_rcv;
+               tcp_seqno = si->io.pck_rcv;
                tcp_ack = si->io.pck_snd;
                tcp_ctl = 0x14; /* RST,ACK */
 
@@ -1123,7 +1123,7 @@ static struct swrap_packet *swrap_marshall_packet(struct socket_info *si,
                src_addr = (const struct sockaddr_in *)si->myname;
                dest_addr = (const struct sockaddr_in *)si->peername;
 
-               tcp_seq = si->io.pck_snd;
+               tcp_seqno = si->io.pck_snd;
                tcp_ack = si->io.pck_rcv;
                tcp_ctl = 0x11; /* FIN, ACK */
 
@@ -1137,7 +1137,7 @@ static struct swrap_packet *swrap_marshall_packet(struct socket_info *si,
                dest_addr = (const struct sockaddr_in *)si->myname;
                src_addr = (const struct sockaddr_in *)si->peername;
 
-               tcp_seq = si->io.pck_rcv;
+               tcp_seqno = si->io.pck_rcv;
                tcp_ack = si->io.pck_snd;
                tcp_ctl = 0x11; /* FIN,ACK */
 
@@ -1151,7 +1151,7 @@ static struct swrap_packet *swrap_marshall_packet(struct socket_info *si,
                src_addr = (const struct sockaddr_in *)si->myname;
                dest_addr = (const struct sockaddr_in *)si->peername;
 
-               tcp_seq = si->io.pck_snd;
+               tcp_seqno = si->io.pck_snd;
                tcp_ack = si->io.pck_rcv;
                tcp_ctl = 0x10; /* ACK */
 
@@ -1164,7 +1164,7 @@ static struct swrap_packet *swrap_marshall_packet(struct socket_info *si,
 
        return swrap_packet_init(&tv, src_addr, dest_addr, si->type,
                                   (const unsigned char *)buf, len,
-                                  tcp_seq, tcp_ack, tcp_ctl, unreachable,
+                                  tcp_seqno, tcp_ack, tcp_ctl, unreachable,
                                   packet_len);
 }
 
diff --git a/lib/subunit/python/subunit/tests/TestUtil.py b/lib/subunit/python/subunit/tests/TestUtil.py
new file mode 100644 (file)
index 0000000..1b5ba9c
--- /dev/null
@@ -0,0 +1,80 @@
+# Copyright (c) 2004 Canonical Limited
+#       Author: Robert Collins <robert.collins@canonical.com>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+#
+
+import sys
+import logging
+import unittest
+
+
+class LogCollector(logging.Handler):
+    def __init__(self):
+        logging.Handler.__init__(self)
+        self.records=[]
+    def emit(self, record):
+        self.records.append(record.getMessage())
+
+
+def makeCollectingLogger():
+    """I make a logger instance that collects its logs for programmatic analysis
+    -> (logger, collector)"""
+    logger=logging.Logger("collector")
+    handler=LogCollector()
+    handler.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))
+    logger.addHandler(handler)
+    return logger, handler
+
+
+def visitTests(suite, visitor):
+    """A foreign method for visiting the tests in a test suite."""
+    for test in suite._tests:
+        #Abusing types to avoid monkey patching unittest.TestCase.
+        # Maybe that would be better?
+        try:
+            test.visit(visitor)
+        except AttributeError:
+            if isinstance(test, unittest.TestCase):
+                visitor.visitCase(test)
+            elif isinstance(test, unittest.TestSuite):
+                visitor.visitSuite(test)
+                visitTests(test, visitor)
+            else:
+                print "unvisitable non-unittest.TestCase element %r (%r)" % (test, test.__class__)
+
+
+class TestSuite(unittest.TestSuite):
+    """I am an extended TestSuite with a visitor interface.
+    This is primarily to allow filtering of tests - and suites or
+    more in the future. An iterator of just tests wouldn't scale..."""
+
+    def visit(self, visitor):
+        """visit the composite. Visiting is depth-first.
+        current callbacks are visitSuite and visitCase."""
+        visitor.visitSuite(self)
+        visitTests(self, visitor)
+
+
+class TestLoader(unittest.TestLoader):
+    """Custome TestLoader to set the right TestSuite class."""
+    suiteClass = TestSuite
+
+class TestVisitor(object):
+    """A visitor for Tests"""
+    def visitSuite(self, aTestSuite):
+        pass
+    def visitCase(self, aTestCase):
+        pass
diff --git a/lib/subunit/python/subunit/tests/__init__.py b/lib/subunit/python/subunit/tests/__init__.py
new file mode 100644 (file)
index 0000000..544d0e7
--- /dev/null
@@ -0,0 +1,25 @@
+#
+#  subunit: extensions to python unittest to get test results from subprocesses.
+#  Copyright (C) 2005  Robert Collins <robertc@robertcollins.net>
+#
+#  This program is free software; you can redistribute it and/or modify
+#  it under the terms of the GNU General Public License as published by
+#  the Free Software Foundation; either version 2 of the License, or
+#  (at your option) any later version.
+#
+#  This program is distributed in the hope that it will be useful,
+#  but WITHOUT ANY WARRANTY; without even the implied warranty of
+#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+#  GNU General Public License for more details.
+#
+#  You should have received a copy of the GNU General Public License
+#  along with this program; if not, write to the Free Software
+#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+#
+
+from subunit.tests import TestUtil, test_test_protocol
+
+def test_suite():
+    result = TestUtil.TestSuite()
+    result.addTest(test_test_protocol.test_suite())
+    return result
diff --git a/lib/subunit/python/subunit/tests/sample-script.py b/lib/subunit/python/subunit/tests/sample-script.py
new file mode 100755 (executable)
index 0000000..223d2f5
--- /dev/null
@@ -0,0 +1,11 @@
+#!/usr/bin/env python
+import sys
+print "test old mcdonald"
+print "success old mcdonald"
+print "test bing crosby"
+print "failure bing crosby ["
+print "foo.c:53:ERROR invalid state"
+print "]"
+print "test an error"
+print "error an error"
+sys.exit(0)
diff --git a/lib/subunit/python/subunit/tests/sample-two-script.py b/lib/subunit/python/subunit/tests/sample-two-script.py
new file mode 100755 (executable)
index 0000000..d555084
--- /dev/null
@@ -0,0 +1,7 @@
+#!/usr/bin/env python
+import sys
+print "test old mcdonald"
+print "success old mcdonald"
+print "test bing crosby"
+print "success bing crosby"
+sys.exit(0)
diff --git a/lib/subunit/python/subunit/tests/test_test_protocol.py b/lib/subunit/python/subunit/tests/test_test_protocol.py
new file mode 100644 (file)
index 0000000..af31584
--- /dev/null
@@ -0,0 +1,730 @@
+#
+#  subunit: extensions to python unittest to get test results from subprocesses.
+#  Copyright (C) 2005  Robert Collins <robertc@robertcollins.net>
+#
+#  This program is free software; you can redistribute it and/or modify
+#  it under the terms of the GNU General Public License as published by
+#  the Free Software Foundation; either version 2 of the License, or
+#  (at your option) any later version.
+#
+#  This program is distributed in the hope that it will be useful,
+#  but WITHOUT ANY WARRANTY; without even the implied warranty of
+#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+#  GNU General Public License for more details.
+#
+#  You should have received a copy of the GNU General Public License
+#  along with this program; if not, write to the Free Software
+#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+#
+
+import unittest
+from StringIO import StringIO
+import os
+import subunit
+import sys
+
+try:
+    class MockTestProtocolServerClient(object):
+        """A mock protocol server client to test callbacks."""
+
+        def __init__(self):
+            self.end_calls = []
+            self.error_calls = []
+            self.failure_calls = []
+            self.start_calls = []
+            self.success_calls = []
+            super(MockTestProtocolServerClient, self).__init__()
+
+        def addError(self, test, error):
+            self.error_calls.append((test, error))
+
+        def addFailure(self, test, error):
+            self.failure_calls.append((test, error))
+
+        def addSuccess(self, test):
+            self.success_calls.append(test)
+
+        def stopTest(self, test):
+            self.end_calls.append(test)
+
+        def startTest(self, test):
+            self.start_calls.append(test)
+
+except AttributeError:
+    MockTestProtocolServer = None
+
+
+class TestMockTestProtocolServer(unittest.TestCase):
+
+    def test_start_test(self):
+        protocol = MockTestProtocolServerClient()
+        protocol.startTest(subunit.RemotedTestCase("test old mcdonald"))
+        self.assertEqual(protocol.start_calls,
+                         [subunit.RemotedTestCase("test old mcdonald")])
+        self.assertEqual(protocol.end_calls, [])
+        self.assertEqual(protocol.error_calls, [])
+        self.assertEqual(protocol.failure_calls, [])
+        self.assertEqual(protocol.success_calls, [])
+
+    def test_add_error(self):
+        protocol = MockTestProtocolServerClient()
+        protocol.addError(subunit.RemotedTestCase("old mcdonald"),
+                          subunit.RemoteError("omg it works"))
+        self.assertEqual(protocol.start_calls, [])
+        self.assertEqual(protocol.end_calls, [])
+        self.assertEqual(protocol.error_calls, [(
+                            subunit.RemotedTestCase("old mcdonald"),
+                            subunit.RemoteError("omg it works"))])
+        self.assertEqual(protocol.failure_calls, [])
+        self.assertEqual(protocol.success_calls, [])
+
+    def test_add_failure(self):
+        protocol = MockTestProtocolServerClient()
+        protocol.addFailure(subunit.RemotedTestCase("old mcdonald"),
+                            subunit.RemoteError("omg it works"))
+        self.assertEqual(protocol.start_calls, [])
+        self.assertEqual(protocol.end_calls, [])
+        self.assertEqual(protocol.error_calls, [])
+        self.assertEqual(protocol.failure_calls, [
+                            (subunit.RemotedTestCase("old mcdonald"),
+                             subunit.RemoteError("omg it works"))])
+        self.assertEqual(protocol.success_calls, [])
+
+    def test_add_success(self):
+        protocol = MockTestProtocolServerClient()
+        protocol.addSuccess(subunit.RemotedTestCase("test old mcdonald"))
+        self.assertEqual(protocol.start_calls, [])
+        self.assertEqual(protocol.end_calls, [])
+        self.assertEqual(protocol.error_calls, [])
+        self.assertEqual(protocol.failure_calls, [])
+        self.assertEqual(protocol.success_calls,
+                         [subunit.RemotedTestCase("test old mcdonald")])
+
+    def test_end_test(self):
+        protocol = MockTestProtocolServerClient()
+        protocol.stopTest(subunit.RemotedTestCase("test old mcdonald"))
+        self.assertEqual(protocol.end_calls,
+                         [subunit.RemotedTestCase("test old mcdonald")])
+        self.assertEqual(protocol.error_calls, [])
+        self.assertEqual(protocol.failure_calls, [])
+        self.assertEqual(protocol.success_calls, [])
+        self.assertEqual(protocol.start_calls, [])
+
+
+class TestTestImports(unittest.TestCase):
+
+    def test_imports(self):
+        from subunit import TestProtocolServer
+        from subunit import RemotedTestCase
+        from subunit import RemoteError
+        from subunit import ExecTestCase
+        from subunit import IsolatedTestCase
+        from subunit import TestProtocolClient
+
+
+class TestTestProtocolServerPipe(unittest.TestCase):
+
+    def test_story(self):
+        client = unittest.TestResult()
+        protocol = subunit.TestProtocolServer(client)
+        pipe = StringIO("test old mcdonald\n"
+                        "success old mcdonald\n"
+                        "test bing crosby\n"
+                        "failure bing crosby [\n"
+                        "foo.c:53:ERROR invalid state\n"
+                        "]\n"
+                        "test an error\n"
+                        "error an error\n")
+        protocol.readFrom(pipe)
+        mcdonald = subunit.RemotedTestCase("old mcdonald")
+        bing = subunit.RemotedTestCase("bing crosby")
+        an_error = subunit.RemotedTestCase("an error")
+        self.assertEqual(client.errors,
+                         [(an_error, 'RemoteException: \n\n')])
+        self.assertEqual(
+            client.failures,
+            [(bing, "RemoteException: foo.c:53:ERROR invalid state\n\n")])
+        self.assertEqual(client.testsRun, 3)
+
+
+class TestTestProtocolServerStartTest(unittest.TestCase):
+
+    def setUp(self):
+        self.client = MockTestProtocolServerClient()
+        self.protocol = subunit.TestProtocolServer(self.client)
+
+    def test_start_test(self):
+        self.protocol.lineReceived("test old mcdonald\n")
+        self.assertEqual(self.client.start_calls,
+                         [subunit.RemotedTestCase("old mcdonald")])
+
+    def test_start_testing(self):
+        self.protocol.lineReceived("testing old mcdonald\n")
+        self.assertEqual(self.client.start_calls,
+                         [subunit.RemotedTestCase("old mcdonald")])
+
+    def test_start_test_colon(self):
+        self.protocol.lineReceived("test: old mcdonald\n")
+        self.assertEqual(self.client.start_calls,
+                         [subunit.RemotedTestCase("old mcdonald")])
+
+    def test_start_testing_colon(self):
+        self.protocol.lineReceived("testing: old mcdonald\n")
+        self.assertEqual(self.client.start_calls,
+                         [subunit.RemotedTestCase("old mcdonald")])
+
+
+class TestTestProtocolServerPassThrough(unittest.TestCase):
+
+    def setUp(self):
+        from StringIO import StringIO
+        self.stdout = StringIO()
+        self.test = subunit.RemotedTestCase("old mcdonald")
+        self.client = MockTestProtocolServerClient()
+        self.protocol = subunit.TestProtocolServer(self.client, self.stdout)
+
+    def keywords_before_test(self):
+        self.protocol.lineReceived("failure a\n")
+        self.protocol.lineReceived("failure: a\n")
+        self.protocol.lineReceived("error a\n")
+        self.protocol.lineReceived("error: a\n")
+        self.protocol.lineReceived("success a\n")
+        self.protocol.lineReceived("success: a\n")
+        self.protocol.lineReceived("successful a\n")
+        self.protocol.lineReceived("successful: a\n")
+        self.protocol.lineReceived("]\n")
+        self.assertEqual(self.stdout.getvalue(), "failure a\n"
+                                                 "failure: a\n"
+                                                 "error a\n"
+                                                 "error: a\n"
+                                                 "success a\n"
+                                                 "success: a\n"
+                                                 "successful a\n"
+                                                 "successful: a\n"
+                                                 "]\n")
+
+    def test_keywords_before_test(self):
+        self.keywords_before_test()
+        self.assertEqual(self.client.start_calls, [])
+        self.assertEqual(self.client.error_calls, [])
+        self.assertEqual(self.client.failure_calls, [])
+        self.assertEqual(self.client.success_calls, [])
+
+    def test_keywords_after_error(self):
+        self.protocol.lineReceived("test old mcdonald\n")
+        self.protocol.lineReceived("error old mcdonald\n")
+        self.keywords_before_test()
+        self.assertEqual(self.client.start_calls, [self.test])
+        self.assertEqual(self.client.end_calls, [self.test])
+        self.assertEqual(self.client.error_calls,
+                         [(self.test, subunit.RemoteError(""))])
+        self.assertEqual(self.client.failure_calls, [])
+        self.assertEqual(self.client.success_calls, [])
+
+    def test_keywords_after_failure(self):
+        self.protocol.lineReceived("test old mcdonald\n")
+        self.protocol.lineReceived("failure old mcdonald\n")
+        self.keywords_before_test()
+        self.assertEqual(self.client.start_calls, [self.test])
+        self.assertEqual(self.client.end_calls, [self.test])
+        self.assertEqual(self.client.error_calls, [])
+        self.assertEqual(self.client.failure_calls,
+                         [(self.test, subunit.RemoteError())])
+        self.assertEqual(self.client.success_calls, [])
+
+    def test_keywords_after_success(self):
+        self.protocol.lineReceived("test old mcdonald\n")
+        self.protocol.lineReceived("success old mcdonald\n")
+        self.keywords_before_test()
+        self.assertEqual(self.client.start_calls, [self.test])
+        self.assertEqual(self.client.end_calls, [self.test])
+        self.assertEqual(self.client.error_calls, [])
+        self.assertEqual(self.client.failure_calls, [])
+        self.assertEqual(self.client.success_calls, [self.test])
+
+    def test_keywords_after_test(self):
+        self.protocol.lineReceived("test old mcdonald\n")
+        self.protocol.lineReceived("test old mcdonald\n")
+        self.protocol.lineReceived("failure a\n")
+        self.protocol.lineReceived("failure: a\n")
+        self.protocol.lineReceived("error a\n")
+        self.protocol.lineReceived("error: a\n")
+        self.protocol.lineReceived("success a\n")
+        self.protocol.lineReceived("success: a\n")
+        self.protocol.lineReceived("successful a\n")
+        self.protocol.lineReceived("successful: a\n")
+        self.protocol.lineReceived("]\n")
+        self.protocol.lineReceived("failure old mcdonald\n")
+        self.assertEqual(self.stdout.getvalue(), "test old mcdonald\n"
+                                                 "failure a\n"
+                                                 "failure: a\n"
+                                                 "error a\n"
+                                                 "error: a\n"
+                                                 "success a\n"
+                                                 "success: a\n"
+                                                 "successful a\n"
+                                                 "successful: a\n"
+                                                 "]\n")
+        self.assertEqual(self.client.start_calls, [self.test])
+        self.assertEqual(self.client.end_calls, [self.test])
+        self.assertEqual(self.client.failure_calls,
+                         [(self.test, subunit.RemoteError())])
+        self.assertEqual(self.client.error_calls, [])
+        self.assertEqual(self.client.success_calls, [])
+
+    def test_keywords_during_failure(self):
+        self.protocol.lineReceived("test old mcdonald\n")
+        self.protocol.lineReceived("failure: old mcdonald [\n")
+        self.protocol.lineReceived("test old mcdonald\n")
+        self.protocol.lineReceived("failure a\n")
+        self.protocol.lineReceived("failure: a\n")
+        self.protocol.lineReceived("error a\n")
+        self.protocol.lineReceived("error: a\n")
+        self.protocol.lineReceived("success a\n")
+        self.protocol.lineReceived("success: a\n")
+        self.protocol.lineReceived("successful a\n")
+        self.protocol.lineReceived("successful: a\n")
+        self.protocol.lineReceived(" ]\n")
+        self.protocol.lineReceived("]\n")
+        self.assertEqual(self.stdout.getvalue(), "")
+        self.assertEqual(self.client.start_calls, [self.test])
+        self.assertEqual(self.client.failure_calls,
+                         [(self.test, subunit.RemoteError("test old mcdonald\n"
+                                                  "failure a\n"
+                                                  "failure: a\n"
+                                                  "error a\n"
+                                                  "error: a\n"
+                                                  "success a\n"
+                                                  "success: a\n"
+                                                  "successful a\n"
+                                                  "successful: a\n"
+                                                  "]\n"))])
+        self.assertEqual(self.client.end_calls, [self.test])
+        self.assertEqual(self.client.error_calls, [])
+        self.assertEqual(self.client.success_calls, [])
+
+    def test_stdout_passthrough(self):
+        """Lines received which cannot be interpreted as any protocol action
+        should be passed through to sys.stdout.
+        """
+        bytes = "randombytes\n"
+        self.protocol.lineReceived(bytes)
+        self.assertEqual(self.stdout.getvalue(), bytes)
+
+
+class TestTestProtocolServerLostConnection(unittest.TestCase):
+
+    def setUp(self):
+        self.client = MockTestProtocolServerClient()
+        self.protocol = subunit.TestProtocolServer(self.client)
+        self.test = subunit.RemotedTestCase("old mcdonald")
+
+    def test_lost_connection_no_input(self):
+        self.protocol.lostConnection()
+        self.assertEqual(self.client.start_calls, [])
+        self.assertEqual(self.client.error_calls, [])
+        self.assertEqual(self.client.failure_calls, [])
+        self.assertEqual(self.client.success_calls, [])
+
+    def test_lost_connection_after_start(self):
+        self.protocol.lineReceived("test old mcdonald\n")
+        self.protocol.lostConnection()
+        self.assertEqual(self.client.start_calls, [self.test])
+        self.assertEqual(self.client.end_calls, [self.test])
+        self.assertEqual(self.client.error_calls, [
+            (self.test, subunit.RemoteError("lost connection during "
+                                            "test 'old mcdonald'"))])
+        self.assertEqual(self.client.failure_calls, [])
+        self.assertEqual(self.client.success_calls, [])
+
+    def test_lost_connected_after_error(self):
+        self.protocol.lineReceived("test old mcdonald\n")
+        self.protocol.lineReceived("error old mcdonald\n")
+        self.protocol.lostConnection()
+        self.assertEqual(self.client.start_calls, [self.test])
+        self.assertEqual(self.client.failure_calls, [])
+        self.assertEqual(self.client.end_calls, [self.test])
+        self.assertEqual(self.client.error_calls, [
+            (self.test, subunit.RemoteError(""))])
+        self.assertEqual(self.client.success_calls, [])
+
+    def test_lost_connection_during_error(self):
+        self.protocol.lineReceived("test old mcdonald\n")
+        self.protocol.lineReceived("error old mcdonald [\n")
+        self.protocol.lostConnection()
+        self.assertEqual(self.client.start_calls, [self.test])
+        self.assertEqual(self.client.end_calls, [self.test])
+        self.assertEqual(self.client.error_calls, [
+            (self.test, subunit.RemoteError("lost connection during error "
+                                            "report of test 'old mcdonald'"))])
+        self.assertEqual(self.client.failure_calls, [])
+        self.assertEqual(self.client.success_calls, [])
+
+    def test_lost_connected_after_failure(self):
+        self.protocol.lineReceived("test old mcdonald\n")
+        self.protocol.lineReceived("failure old mcdonald\n")
+        self.protocol.lostConnection()
+        test = subunit.RemotedTestCase("old mcdonald")
+        self.assertEqual(self.client.start_calls, [self.test])
+        self.assertEqual(self.client.end_calls, [self.test])
+        self.assertEqual(self.client.error_calls, [])
+        self.assertEqual(self.client.failure_calls,
+                         [(self.test, subunit.RemoteError())])
+        self.assertEqual(self.client.success_calls, [])
+
+    def test_lost_connection_during_failure(self):
+        self.protocol.lineReceived("test old mcdonald\n")
+        self.protocol.lineReceived("failure old mcdonald [\n")
+        self.protocol.lostConnection()
+        self.assertEqual(self.client.start_calls, [self.test])
+        self.assertEqual(self.client.end_calls, [self.test])
+        self.assertEqual(self.client.error_calls,
+                         [(self.test,
+                           subunit.RemoteError("lost connection during "
+                                               "failure report"
+                                               " of test 'old mcdonald'"))])
+        self.assertEqual(self.client.failure_calls, [])
+        self.assertEqual(self.client.success_calls, [])
+
+    def test_lost_connection_after_success(self):
+        self.protocol.lineReceived("test old mcdonald\n")
+        self.protocol.lineReceived("success old mcdonald\n")
+        self.protocol.lostConnection()
+        self.assertEqual(self.client.start_calls, [self.test])
+        self.assertEqual(self.client.end_calls, [self.test])
+        self.assertEqual(self.client.error_calls, [])
+        self.assertEqual(self.client.failure_calls, [])
+        self.assertEqual(self.client.success_calls, [self.test])
+
+
+class TestTestProtocolServerAddError(unittest.TestCase):
+
+    def setUp(self):
+        self.client = MockTestProtocolServerClient()
+        self.protocol = subunit.TestProtocolServer(self.client)
+        self.protocol.lineReceived("test mcdonalds farm\n")
+        self.test = subunit.RemotedTestCase("mcdonalds farm")
+
+    def simple_error_keyword(self, keyword):
+        self.protocol.lineReceived("%s mcdonalds farm\n" % keyword)
+        self.assertEqual(self.client.start_calls, [self.test])
+        self.assertEqual(self.client.end_calls, [self.test])
+        self.assertEqual(self.client.error_calls, [
+            (self.test, subunit.RemoteError(""))])
+        self.assertEqual(self.client.failure_calls, [])
+
+    def test_simple_error(self):
+        self.simple_error_keyword("error")
+
+    def test_simple_error_colon(self):
+        self.simple_error_keyword("error:")
+
+    def test_error_empty_message(self):
+        self.protocol.lineReceived("error mcdonalds farm [\n")
+        self.protocol.lineReceived("]\n")
+        self.assertEqual(self.client.start_calls, [self.test])
+        self.assertEqual(self.client.end_calls, [self.test])
+        self.assertEqual(self.client.error_calls, [
+            (self.test, subunit.RemoteError(""))])
+        self.assertEqual(self.client.failure_calls, [])
+
+    def error_quoted_bracket(self, keyword):
+        self.protocol.lineReceived("%s mcdonalds farm [\n" % keyword)
+        self.protocol.lineReceived(" ]\n")
+        self.protocol.lineReceived("]\n")
+        self.assertEqual(self.client.start_calls, [self.test])
+        self.assertEqual(self.client.end_calls, [self.test])
+        self.assertEqual(self.client.error_calls, [
+            (self.test, subunit.RemoteError("]\n"))])
+        self.assertEqual(self.client.failure_calls, [])
+
+    def test_error_quoted_bracket(self):
+        self.error_quoted_bracket("error")
+
+    def test_error_colon_quoted_bracket(self):
+        self.error_quoted_bracket("error:")
+
+
+class TestTestProtocolServerAddFailure(unittest.TestCase):
+
+    def setUp(self):
+        self.client = MockTestProtocolServerClient()
+        self.protocol = subunit.TestProtocolServer(self.client)
+        self.protocol.lineReceived("test mcdonalds farm\n")
+        self.test = subunit.RemotedTestCase("mcdonalds farm")
+
+    def simple_failure_keyword(self, keyword):
+        self.protocol.lineReceived("%s mcdonalds farm\n" % keyword)
+        self.assertEqual(self.client.start_calls, [self.test])
+        self.assertEqual(self.client.end_calls, [self.test])
+        self.assertEqual(self.client.error_calls, [])
+        self.assertEqual(self.client.failure_calls,
+                         [(self.test, subunit.RemoteError())])
+
+    def test_simple_failure(self):
+        self.simple_failure_keyword("failure")
+
+    def test_simple_failure_colon(self):
+        self.simple_failure_keyword("failure:")
+
+    def test_failure_empty_message(self):
+        self.protocol.lineReceived("failure mcdonalds farm [\n")
+        self.protocol.lineReceived("]\n")
+        self.assertEqual(self.client.start_calls, [self.test])
+        self.assertEqual(self.client.end_calls, [self.test])
+        self.assertEqual(self.client.error_calls, [])
+        self.assertEqual(self.client.failure_calls,
+                         [(self.test, subunit.RemoteError())])
+
+    def failure_quoted_bracket(self, keyword):
+        self.protocol.lineReceived("%s mcdonalds farm [\n" % keyword)
+        self.protocol.lineReceived(" ]\n")
+        self.protocol.lineReceived("]\n")
+        self.assertEqual(self.client.start_calls, [self.test])
+        self.assertEqual(self.client.end_calls, [self.test])
+        self.assertEqual(self.client.error_calls, [])
+        self.assertEqual(self.client.failure_calls,
+                         [(self.test, subunit.RemoteError("]\n"))])
+
+    def test_failure_quoted_bracket(self):
+        self.failure_quoted_bracket("failure")
+
+    def test_failure_colon_quoted_bracket(self):
+        self.failure_quoted_bracket("failure:")
+
+
+class TestTestProtocolServerAddSuccess(unittest.TestCase):
+
+    def setUp(self):
+        self.client = MockTestProtocolServerClient()
+        self.protocol = subunit.TestProtocolServer(self.client)
+        self.protocol.lineReceived("test mcdonalds farm\n")
+        self.test = subunit.RemotedTestCase("mcdonalds farm")
+
+    def simple_success_keyword(self, keyword):
+        self.protocol.lineReceived("%s mcdonalds farm\n" % keyword)
+        self.assertEqual(self.client.start_calls, [self.test])
+        self.assertEqual(self.client.end_calls, [self.test])
+        self.assertEqual(self.client.error_calls, [])
+        self.assertEqual(self.client.success_calls, [self.test])
+
+    def test_simple_success(self):
+        self.simple_success_keyword("failure")
+
+    def test_simple_success_colon(self):
+        self.simple_success_keyword("failure:")
+
+    def test_simple_success(self):
+        self.simple_success_keyword("successful")
+
+    def test_simple_success_colon(self):
+        self.simple_success_keyword("successful:")
+
+
+class TestRemotedTestCase(unittest.TestCase):
+
+    def test_simple(self):
+        test = subunit.RemotedTestCase("A test description")
+        self.assertRaises(NotImplementedError, test.setUp)
+        self.assertRaises(NotImplementedError, test.tearDown)
+        self.assertEqual("A test description",
+                         test.shortDescription())
+        self.assertEqual("subunit.RemotedTestCase.A test description",
+                         test.id())
+        self.assertEqual("A test description (subunit.RemotedTestCase)", "%s" % test)
+        self.assertEqual("<subunit.RemotedTestCase description="
+                         "'A test description'>", "%r" % test)
+        result = unittest.TestResult()
+        test.run(result)
+        self.assertEqual([(test, "RemoteException: "
+                                 "Cannot run RemotedTestCases.\n\n")],
+                         result.errors)
+        self.assertEqual(1, result.testsRun)
+        another_test = subunit.RemotedTestCase("A test description")
+        self.assertEqual(test, another_test)
+        different_test = subunit.RemotedTestCase("ofo")
+        self.assertNotEqual(test, different_test)
+        self.assertNotEqual(another_test, different_test)
+
+
+class TestRemoteError(unittest.TestCase):
+
+    def test_eq(self):
+        error = subunit.RemoteError("Something went wrong")
+        another_error = subunit.RemoteError("Something went wrong")
+        different_error = subunit.RemoteError("boo!")
+        self.assertEqual(error, another_error)
+        self.assertNotEqual(error, different_error)
+        self.assertNotEqual(different_error, another_error)
+
+    def test_empty_constructor(self):
+        self.assertEqual(subunit.RemoteError(), subunit.RemoteError(""))
+
+
+class TestExecTestCase(unittest.TestCase):
+
+    class SampleExecTestCase(subunit.ExecTestCase):
+
+        def test_sample_method(self):
+            """sample-script.py"""
+            # the sample script runs three tests, one each
+            # that fails, errors and succeeds
+
+
+    def test_construct(self):
+        test = self.SampleExecTestCase("test_sample_method")
+        self.assertEqual(test.script,
+                         subunit.join_dir(__file__, 'sample-script.py'))
+
+    def test_run(self):
+        runner = MockTestProtocolServerClient()
+        test = self.SampleExecTestCase("test_sample_method")
+        test.run(runner)
+        mcdonald = subunit.RemotedTestCase("old mcdonald")
+        bing = subunit.RemotedTestCase("bing crosby")
+        an_error = subunit.RemotedTestCase("an error")
+        self.assertEqual(runner.error_calls,
+                         [(an_error, subunit.RemoteError())])
+        self.assertEqual(runner.failure_calls,
+                         [(bing,
+                           subunit.RemoteError(
+                            "foo.c:53:ERROR invalid state\n"))])
+        self.assertEqual(runner.start_calls, [mcdonald, bing, an_error])
+        self.assertEqual(runner.end_calls, [mcdonald, bing, an_error])
+
+    def test_debug(self):
+        test = self.SampleExecTestCase("test_sample_method")
+        test.debug()
+
+    def test_count_test_cases(self):
+        """TODO run the child process and count responses to determine the count."""
+
+    def test_join_dir(self):
+        sibling = subunit.join_dir(__file__, 'foo')
+        expected = '%s/foo' % (os.path.split(__file__)[0],)
+        self.assertEqual(sibling, expected)
+
+
+class DoExecTestCase(subunit.ExecTestCase):
+
+    def test_working_script(self):
+        """sample-two-script.py"""
+
+
+class TestIsolatedTestCase(unittest.TestCase):
+
+    class SampleIsolatedTestCase(subunit.IsolatedTestCase):
+
+        SETUP = False
+        TEARDOWN = False
+        TEST = False
+
+        def setUp(self):
+            TestIsolatedTestCase.SampleIsolatedTestCase.SETUP = True
+
+        def tearDown(self):
+            TestIsolatedTestCase.SampleIsolatedTestCase.TEARDOWN = True
+
+        def test_sets_global_state(self):
+            TestIsolatedTestCase.SampleIsolatedTestCase.TEST = True
+
+
+    def test_construct(self):
+        test = self.SampleIsolatedTestCase("test_sets_global_state")
+
+    def test_run(self):
+        result = unittest.TestResult()
+        test = self.SampleIsolatedTestCase("test_sets_global_state")
+        test.run(result)
+        self.assertEqual(result.testsRun, 1)
+        self.assertEqual(self.SampleIsolatedTestCase.SETUP, False)
+        self.assertEqual(self.SampleIsolatedTestCase.TEARDOWN, False)
+        self.assertEqual(self.SampleIsolatedTestCase.TEST, False)
+
+    def test_debug(self):
+        pass
+        #test = self.SampleExecTestCase("test_sample_method")
+        #test.debug()
+
+
+class TestIsolatedTestSuite(unittest.TestCase):
+
+    class SampleTestToIsolate(unittest.TestCase):
+
+        SETUP = False
+        TEARDOWN = False
+        TEST = False
+
+        def setUp(self):
+            TestIsolatedTestSuite.SampleTestToIsolate.SETUP = True
+
+        def tearDown(self):
+            TestIsolatedTestSuite.SampleTestToIsolate.TEARDOWN = True
+
+        def test_sets_global_state(self):
+            TestIsolatedTestSuite.SampleTestToIsolate.TEST = True
+
+
+    def test_construct(self):
+        suite = subunit.IsolatedTestSuite()
+
+    def test_run(self):
+        result = unittest.TestResult()
+        suite = subunit.IsolatedTestSuite()
+        sub_suite = unittest.TestSuite()
+        sub_suite.addTest(self.SampleTestToIsolate("test_sets_global_state"))
+        sub_suite.addTest(self.SampleTestToIsolate("test_sets_global_state"))
+        suite.addTest(sub_suite)
+        suite.addTest(self.SampleTestToIsolate("test_sets_global_state"))
+        suite.run(result)
+        self.assertEqual(result.testsRun, 3)
+        self.assertEqual(self.SampleTestToIsolate.SETUP, False)
+        self.assertEqual(self.SampleTestToIsolate.TEARDOWN, False)
+        self.assertEqual(self.SampleTestToIsolate.TEST, False)
+
+
+class TestTestProtocolClient(unittest.TestCase):
+
+    def setUp(self):
+        self.io = StringIO()
+        self.protocol = subunit.TestProtocolClient(self.io)
+        self.test = TestTestProtocolClient("test_start_test")
+
+
+    def test_start_test(self):
+        """Test startTest on a TestProtocolClient."""
+        self.protocol.startTest(self.test)
+        self.assertEqual(self.io.getvalue(), "test: %s\n" % self.test.id())
+
+    def test_stop_test(self):
+        """Test stopTest on a TestProtocolClient."""
+        self.protocol.stopTest(self.test)
+        self.assertEqual(self.io.getvalue(), "")
+
+    def test_add_success(self):
+        """Test addSuccess on a TestProtocolClient."""
+        self.protocol.addSuccess(self.test)
+        self.assertEqual(
+            self.io.getvalue(), "successful: %s\n" % self.test.id())
+
+    def test_add_failure(self):
+        """Test addFailure on a TestProtocolClient."""
+        self.protocol.addFailure(self.test, subunit.RemoteError("boo"))
+        self.assertEqual(
+            self.io.getvalue(),
+            'failure: %s [\nRemoteException: boo\n]\n' % self.test.id())
+
+    def test_add_error(self):
+        """Test stopTest on a TestProtocolClient."""
+        self.protocol.addError(self.test, subunit.RemoteError("phwoar"))
+        self.assertEqual(
+            self.io.getvalue(),
+            'error: %s [\n'
+            "RemoteException: phwoar\n"
+            "]\n" % self.test.id())
+
+
+def test_suite():
+    loader = subunit.tests.TestUtil.TestLoader()
+    result = loader.loadTestsFromName(__name__)
+    return result
index 18663b370d9dc4d8b9aaeae28ef40655cd4d97c4..3201fe6f0f01f511e38c8ac58204a42458598278 100644 (file)
@@ -1,5 +1,7 @@
 Using talloc in Samba4
-----------------------
+======================
+
+.. contents::
 
 Andrew Tridgell
 September 2004
@@ -18,7 +20,7 @@ get used to it.
 Perhaps the biggest change from Samba3 is that there is no distinction
 between a "talloc context" and a "talloc pointer". Any pointer
 returned from talloc() is itself a valid talloc context. This means
-you can do this:
+you can do this::
 
   struct foo *X = talloc(mem_ctx, struct foo);
   X->name = talloc_strdup(X, "foo");
@@ -271,7 +273,7 @@ equivalent to:
 =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
 void *talloc_named_const(const void *context, size_t size, const char *name);
 
-This is equivalent to:
+This is equivalent to::
 
    ptr = talloc_size(context, size);
    talloc_set_name_const(ptr, name);
@@ -288,7 +290,7 @@ talloc_set_name() for details.
 void *talloc_init(const char *fmt, ...);
 
 This function creates a zero length named talloc context as a top
-level context. It is equivalent to:
+level context. It is equivalent to::
 
   talloc_named(NULL, 0, fmt, ...);
 
@@ -309,7 +311,7 @@ The talloc_realloc() macro changes the size of a talloc
 pointer. The "count" argument is the number of elements of type "type"
 that you want the resulting pointer to hold. 
 
-talloc_realloc() has the following equivalences:
+talloc_realloc() has the following equivalences::
 
   talloc_realloc(context, NULL, type, 1) ==> talloc(context, type);
   talloc_realloc(context, NULL, type, N) ==> talloc_array(context, type, N);
@@ -490,7 +492,7 @@ This disables tracking of the NULL memory context.
 =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
 (type *)talloc_zero(const void *ctx, type);
 
-The talloc_zero() macro is equivalent to:
+The talloc_zero() macro is equivalent to::
 
   ptr = talloc(ctx, type);
   if (ptr) memset(ptr, 0, sizeof(type));
@@ -505,7 +507,7 @@ The talloc_zero_size() function is useful when you don't have a known type
 =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
 void *talloc_memdup(const void *ctx, const void *p, size_t size);
 
-The talloc_memdup() function is equivalent to:
+The talloc_memdup() function is equivalent to::
 
   ptr = talloc_size(ctx, size);
   if (ptr) memcpy(ptr, p, size);
@@ -514,13 +516,14 @@ The talloc_memdup() function is equivalent to:
 =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
 char *talloc_strdup(const void *ctx, const char *p);
 
-The talloc_strdup() function is equivalent to:
+The talloc_strdup() function is equivalent to::
 
   ptr = talloc_size(ctx, strlen(p)+1);
   if (ptr) memcpy(ptr, p, strlen(p)+1);
 
 This functions sets the name of the new pointer to the passed
-string. This is equivalent to:
+string. This is equivalent to::
+
    talloc_set_name_const(ptr, ptr)
 
 =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
@@ -540,7 +543,8 @@ The talloc_append_string() function appends the given formatted
 string to the given string.
 
 This function sets the name of the new pointer to the new
-string. This is equivalent to:
+string. This is equivalent to::
+
    talloc_set_name_const(ptr, ptr)
 
 =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
@@ -550,7 +554,8 @@ The talloc_vasprintf() function is the talloc equivalent of the C
 library function vasprintf()
 
 This functions sets the name of the new pointer to the new
-string. This is equivalent to:
+string. This is equivalent to::
+
    talloc_set_name_const(ptr, ptr)
 
 
@@ -561,7 +566,8 @@ The talloc_asprintf() function is the talloc equivalent of the C
 library function asprintf()
 
 This functions sets the name of the new pointer to the new
-string. This is equivalent to:
+string. This is equivalent to::
+
    talloc_set_name_const(ptr, ptr)
 
 
@@ -574,7 +580,8 @@ Use this varient when the string in the current talloc buffer may
 have been truncated in length.
 
 This functions sets the name of the new pointer to the new
-string. This is equivalent to:
+string. This is equivalent to::
+
    talloc_set_name_const(ptr, ptr)
 
 
@@ -587,14 +594,15 @@ Use this varient when the string in the current talloc buffer has
 not been changed.
 
 This functions sets the name of the new pointer to the new
-string. This is equivalent to:
+string. This is equivalent to::
+
    talloc_set_name_const(ptr, ptr)
 
 
 =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
 ((type *)talloc_array(const void *ctx, type, uint_t count);
 
-The talloc_array() macro is equivalent to:
+The talloc_array() macro is equivalent to::
 
   (type *)talloc_size(ctx, sizeof(type) * count);
 
@@ -648,7 +656,7 @@ then the pointer is returned. It it doesn't then NULL is returned.
 
 This macro allows you to do type checking on talloc pointers. It is
 particularly useful for void* private pointers. It is equivalent to
-this:
+this::
 
    (type *)talloc_check_name(ptr, #type)
 
@@ -660,7 +668,8 @@ This macro allows you to force the name of a pointer to be a
 particular type. This can be used in conjunction with
 talloc_get_type() to do type checking on void* pointers.
 
-It is equivalent to this:
+It is equivalent to this::
+
    talloc_set_name_const(ptr, #type)
 
 =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
index 4bf2e98e8f1d1257294aa65abba406d43a6ff48a..2feaa6f5f556359268430820b46cfc8704223c3a 100644 (file)
@@ -2,7 +2,7 @@ AC_PREREQ(2.50)
 AC_DEFUN([SMB_MODULE_DEFAULT], [echo -n ""])
 AC_DEFUN([SMB_LIBRARY_ENABLE], [echo -n ""])
 AC_DEFUN([SMB_ENABLE], [echo -n ""])
-AC_INIT(tdb, 1.1.2)
+AC_INIT(tdb, 1.1.3)
 AC_CONFIG_SRCDIR([common/tdb.c])
 AC_CONFIG_HEADER(include/config.h)
 AC_LIBREPLACE_ALL_CHECKS
index ab5d9af8aa874f790bcdbb3a9f307e47a4bb9b59..acfce61ccaf5851cd972fa52cc3d5a426e27202b 100644 (file)
 #include "includes.h"
 #include "../libcli/netlogon.h"
 
+#undef DEBUG
+#define DEBUG(x, y)
+#undef DEBUGLVL
+#define DEBUGLVL(x) false
+#undef DEBUGLEVEL
+#define DEBUGLEVEL 0
+
 NTSTATUS push_netlogon_samlogon_response(DATA_BLOB *data, TALLOC_CTX *mem_ctx,
                                         struct smb_iconv_convenience *iconv_convenience,
                                         struct netlogon_samlogon_response *response)
@@ -30,17 +37,17 @@ NTSTATUS push_netlogon_samlogon_response(DATA_BLOB *data, TALLOC_CTX *mem_ctx,
        if (response->ntver == NETLOGON_NT_VERSION_1) {
                ndr_err = ndr_push_struct_blob(data, mem_ctx,
                                               iconv_convenience,
-                                              &response->nt4,
+                                              &response->data.nt4,
                                               (ndr_push_flags_fn_t)ndr_push_NETLOGON_SAM_LOGON_RESPONSE_NT40);
        } else if (response->ntver & NETLOGON_NT_VERSION_5EX) {
                ndr_err = ndr_push_struct_blob(data, mem_ctx,
                                               iconv_convenience,
-                                              &response->nt5_ex,
+                                              &response->data.nt5_ex,
                                               (ndr_push_flags_fn_t)ndr_push_NETLOGON_SAM_LOGON_RESPONSE_EX_with_flags);
        } else if (response->ntver & NETLOGON_NT_VERSION_5) {
                ndr_err = ndr_push_struct_blob(data, mem_ctx,
                                               iconv_convenience,
-                                              &response->nt5,
+                                              &response->data.nt5,
                                               (ndr_push_flags_fn_t)ndr_push_NETLOGON_SAM_LOGON_RESPONSE);
        } else {
                DEBUG(0, ("Asked to push unknown netlogon response type 0x%02x\n", response->ntver));
@@ -79,11 +86,12 @@ NTSTATUS pull_netlogon_samlogon_response(DATA_BLOB *data, TALLOC_CTX *mem_ctx,
        if (ntver == NETLOGON_NT_VERSION_1) {
                ndr_err = ndr_pull_struct_blob_all(data, mem_ctx,
                                                   iconv_convenience,
-                                                  &response->nt4,
+                                                  &response->data.nt4,
                                                   (ndr_pull_flags_fn_t)ndr_pull_NETLOGON_SAM_LOGON_RESPONSE_NT40);
                response->ntver = NETLOGON_NT_VERSION_1;
                if (NDR_ERR_CODE_IS_SUCCESS(ndr_err) && DEBUGLEVEL >= 10) {
-                       NDR_PRINT_DEBUG(NETLOGON_SAM_LOGON_RESPONSE_NT40, &response->nt4);
+                       NDR_PRINT_DEBUG(NETLOGON_SAM_LOGON_RESPONSE_NT40,
+                                       &response->data.nt4);
                }
 
        } else if (ntver & NETLOGON_NT_VERSION_5EX) {
@@ -92,7 +100,9 @@ NTSTATUS pull_netlogon_samlogon_response(DATA_BLOB *data, TALLOC_CTX *mem_ctx,
                if (!ndr) {
                        return NT_STATUS_NO_MEMORY;
                }
-               ndr_err = ndr_pull_NETLOGON_SAM_LOGON_RESPONSE_EX_with_flags(ndr, NDR_SCALARS|NDR_BUFFERS, &response->nt5_ex, ntver);
+               ndr_err = ndr_pull_NETLOGON_SAM_LOGON_RESPONSE_EX_with_flags(
+                       ndr, NDR_SCALARS|NDR_BUFFERS, &response->data.nt5_ex,
+                       ntver);
                if (ndr->offset < ndr->data_size) {
                        ndr_err = ndr_pull_error(ndr, NDR_ERR_UNREAD_BYTES,
                                                 "not all bytes consumed ofs[%u] size[%u]",
@@ -100,17 +110,19 @@ NTSTATUS pull_netlogon_samlogon_response(DATA_BLOB *data, TALLOC_CTX *mem_ctx,
                }
                response->ntver = NETLOGON_NT_VERSION_5EX;
                if (NDR_ERR_CODE_IS_SUCCESS(ndr_err) && DEBUGLEVEL >= 10) {
-                       NDR_PRINT_DEBUG(NETLOGON_SAM_LOGON_RESPONSE_EX, &response->nt5_ex);
+                       NDR_PRINT_DEBUG(NETLOGON_SAM_LOGON_RESPONSE_EX,
+                                       &response->data.nt5_ex);
                }
 
        } else if (ntver & NETLOGON_NT_VERSION_5) {
                ndr_err = ndr_pull_struct_blob_all(data, mem_ctx,
                                                   iconv_convenience,
-                                                  &response->nt5,
+                                                  &response->data.nt5,
                                                   (ndr_pull_flags_fn_t)ndr_pull_NETLOGON_SAM_LOGON_RESPONSE);
                response->ntver = NETLOGON_NT_VERSION_5;
                if (NDR_ERR_CODE_IS_SUCCESS(ndr_err) && DEBUGLEVEL >= 10) {
-                       NDR_PRINT_DEBUG(NETLOGON_SAM_LOGON_RESPONSE, &response->nt5);
+                       NDR_PRINT_DEBUG(NETLOGON_SAM_LOGON_RESPONSE,
+                                       &response->data.nt5);
                }
        } else {
                DEBUG(2,("failed to parse netlogon response of type 0x%02x - unknown response type\n",
@@ -137,34 +149,34 @@ void map_netlogon_samlogon_response(struct netlogon_samlogon_response *response)
                break;
        case NETLOGON_NT_VERSION_5:
                ZERO_STRUCT(response_5_ex);
-               response_5_ex.command = response->nt5.command;
-               response_5_ex.pdc_name = response->nt5.pdc_name;
-               response_5_ex.user_name = response->nt5.user_name;
-               response_5_ex.domain = response->nt5.domain_name;
-               response_5_ex.domain_uuid = response->nt5.domain_uuid;
-               response_5_ex.forest = response->nt5.forest;
-               response_5_ex.dns_domain = response->nt5.dns_domain;
-               response_5_ex.pdc_dns_name = response->nt5.pdc_dns_name;
-               response_5_ex.sockaddr.pdc_ip = response->nt5.pdc_ip;
-               response_5_ex.server_type = response->nt5.server_type;
-               response_5_ex.nt_version = response->nt5.nt_version;
-               response_5_ex.lmnt_token = response->nt5.lmnt_token;
-               response_5_ex.lm20_token = response->nt5.lm20_token;
+               response_5_ex.command = response->data.nt5.command;
+               response_5_ex.pdc_name = response->data.nt5.pdc_name;
+               response_5_ex.user_name = response->data.nt5.user_name;
+               response_5_ex.domain = response->data.nt5.domain_name;
+               response_5_ex.domain_uuid = response->data.nt5.domain_uuid;
+               response_5_ex.forest = response->data.nt5.forest;
+               response_5_ex.dns_domain = response->data.nt5.dns_domain;
+               response_5_ex.pdc_dns_name = response->data.nt5.pdc_dns_name;
+               response_5_ex.sockaddr.pdc_ip = response->data.nt5.pdc_ip;
+               response_5_ex.server_type = response->data.nt5.server_type;
+               response_5_ex.nt_version = response->data.nt5.nt_version;
+               response_5_ex.lmnt_token = response->data.nt5.lmnt_token;
+               response_5_ex.lm20_token = response->data.nt5.lm20_token;
                response->ntver = NETLOGON_NT_VERSION_5EX;
-               response->nt5_ex = response_5_ex;
+               response->data.nt5_ex = response_5_ex;
                break;
 
        case NETLOGON_NT_VERSION_1:
                ZERO_STRUCT(response_5_ex);
-               response_5_ex.command = response->nt4.command;
-               response_5_ex.pdc_name = response->nt4.server;
-               response_5_ex.user_name = response->nt4.user_name;
-               response_5_ex.domain = response->nt4.domain;
-               response_5_ex.nt_version = response->nt4.nt_version;
-               response_5_ex.lmnt_token = response->nt4.lmnt_token;
-               response_5_ex.lm20_token = response->nt4.lm20_token;
+               response_5_ex.command = response->data.nt4.command;
+               response_5_ex.pdc_name = response->data.nt4.server;
+               response_5_ex.user_name = response->data.nt4.user_name;
+               response_5_ex.domain = response->data.nt4.domain;
+               response_5_ex.nt_version = response->data.nt4.nt_version;
+               response_5_ex.lmnt_token = response->data.nt4.lmnt_token;
+               response_5_ex.lm20_token = response->data.nt4.lm20_token;
                response->ntver = NETLOGON_NT_VERSION_5EX;
-               response->nt5_ex = response_5_ex;
+               response->data.nt5_ex = response_5_ex;
                break;
        }
        return;
@@ -178,7 +190,9 @@ NTSTATUS push_nbt_netlogon_response(DATA_BLOB *data, TALLOC_CTX *mem_ctx,
        enum ndr_err_code ndr_err;
        switch (response->response_type) {
        case NETLOGON_GET_PDC:
-               ndr_err = ndr_push_struct_blob(data, mem_ctx, iconv_convenience, &response->get_pdc,
+               ndr_err = ndr_push_struct_blob(data, mem_ctx,
+                                              iconv_convenience,
+                                              &response->data.get_pdc,
                                               (ndr_push_flags_fn_t)ndr_push_nbt_netlogon_response_from_pdc);
                if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
                        status = ndr_map_error2ntstatus(ndr_err);
@@ -192,7 +206,9 @@ NTSTATUS push_nbt_netlogon_response(DATA_BLOB *data, TALLOC_CTX *mem_ctx,
                status = NT_STATUS_OK;
                break;
        case NETLOGON_SAMLOGON:
-               status = push_netlogon_samlogon_response(data, mem_ctx, iconv_convenience, &response->samlogon);
+               status = push_netlogon_samlogon_response(
+                       data, mem_ctx, iconv_convenience,
+                       &response->data.samlogon);
                break;
        }
        return status;
@@ -214,7 +230,9 @@ NTSTATUS pull_nbt_netlogon_response(DATA_BLOB *data, TALLOC_CTX *mem_ctx,
 
        switch (command) {
        case NETLOGON_RESPONSE_FROM_PDC:
-               ndr_err = ndr_pull_struct_blob_all(data, mem_ctx, iconv_convenience, &response->get_pdc,
+               ndr_err = ndr_pull_struct_blob_all(data, mem_ctx,
+                                                  iconv_convenience,
+                                                  &response->data.get_pdc,
                                                   (ndr_pull_flags_fn_t)ndr_pull_nbt_netlogon_response_from_pdc);
                if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
                        status = ndr_map_error2ntstatus(ndr_err);
@@ -234,7 +252,9 @@ NTSTATUS pull_nbt_netlogon_response(DATA_BLOB *data, TALLOC_CTX *mem_ctx,
        case LOGON_SAM_LOGON_RESPONSE_EX:
        case LOGON_SAM_LOGON_PAUSE_RESPONSE_EX:
        case LOGON_SAM_LOGON_USER_UNKNOWN_EX:
-               status = pull_netlogon_samlogon_response(data, mem_ctx, iconv_convenience, &response->samlogon);
+               status = pull_netlogon_samlogon_response(
+                       data, mem_ctx, iconv_convenience,
+                       &response->data.samlogon);
                response->response_type = NETLOGON_SAMLOGON;
                break;
 
index 8bd9d0d90a7b5e770ea7b1ce79af5f477422e69b..6ca3de3366ea35ddc1d950577957981b8fa49aa8 100644 (file)
@@ -36,7 +36,7 @@ struct netlogon_samlogon_response
                struct NETLOGON_SAM_LOGON_RESPONSE_NT40 nt4;
                struct NETLOGON_SAM_LOGON_RESPONSE nt5;
                struct NETLOGON_SAM_LOGON_RESPONSE_EX nt5_ex;
-       };
+       } data;
 
 };
 
@@ -46,7 +46,7 @@ struct nbt_netlogon_response
        union {
                struct nbt_netlogon_response_from_pdc get_pdc;
                struct netlogon_samlogon_response samlogon;
-       };
+       } data;
 };
 
 #include "../libcli/netlogon_proto.h"
index 8886441a75686d88d231acc2c8d94051d45c3301..87ae0c5fd33ef07217dbfd668739a333cad4f200 100644 (file)
--- a/pidl/TODO
+++ b/pidl/TODO
@@ -1,8 +1,5 @@
 - warn when union instances don't have a discriminant
 
-- EJS output backend shouldn't use the NDR levels stuff but instead 
-  as the "C levels" and NDR levels don't necessarily match.
-
 - true multiple dimension array / strings in arrays support
 
 - compatibility mode for generating MIDL-readable data:
index 07c8647ecd4d26f8221b75d4e62958cd3c4b06a5..45582f5d568b54fce90aa66f13759d710978c3be 100644 (file)
@@ -1,13 +1,13 @@
 PIDL = $(PERL) $(pidldir)/pidl
 
 $(pidldir)/Makefile: $(pidldir)/Makefile.PL
-       cd $(pidldir) && $(PERL) Makefile.PL PREFIX=$(prefix)
+       @cd $(pidldir) && $(PERL) Makefile.PL PREFIX=$(prefix)
 
 pidl-testcov: $(pidldir)/Makefile
        cd $(pidldir) && cover -test
 
 installpidl:: $(pidldir)/Makefile
-       $(MAKE) -C $(pidldir) install_vendor VENDORPREFIX=$(prefix) \
+       @$(MAKE) -C $(pidldir) install_vendor VENDORPREFIX=$(prefix) \
                                           INSTALLVENDORLIB=$(datarootdir)/perl5 \
                                                                   INSTALLVENDORBIN=$(bindir) \
                                                                   INSTALLVENDORSCRIPT=$(bindir) \
index ad8c76f62263634ca92836551fee72488e939629..c49cdfb795cac9139dd3cfbf548a70d4f18a5ceb 100644 (file)
@@ -57,6 +57,10 @@ sub ODL2IDL
                if ($x->{TYPE} eq "IMPORT") {
                        foreach my $idl_file (@{$x->{PATHS}}) {
                                $idl_file = unmake_str($idl_file);
+                               unless (-f "$basedir/$idl_file") {
+                                       error($x, "Unable to open include file `$idl_file'");
+                                       next;
+                               }
                                my $podl = Parse::Pidl::IDL::parse_file("$basedir/$idl_file", $opt_incdirs);
                                if (defined(@$podl)) {
                                        require Parse::Pidl::Typelist;
index 74cec5a8274c3427371f61f29d3777fa1e354770..fc64c35fca1858da2f57f42cf684c4e316d6f26b 100644 (file)
@@ -1173,6 +1173,7 @@ sub Parse($$$$$)
        $self->pidl("{");
        $self->indent;
        $self->pidl("PyObject *m;");
+       $self->pidl("NTSTATUS status;");
        $self->pidl("");
 
        foreach (@{$self->{ready_types}}) {
@@ -1208,6 +1209,15 @@ sub Parse($$$$$)
                $self->pidl("PyModule_AddObject(m, \"$object_name\", $c_name);");
        }
 
+       $self->pidl("");
+       $self->pidl("status = dcerpc_init();");
+       $self->pidl("if (!NT_STATUS_IS_OK(status)) {");
+       $self->indent;
+       $self->pidl("PyErr_SetNTSTATUS(status);");
+       $self->pidl("return;");
+       $self->deindent;
+       $self->pidl("}");
+
        $self->deindent;
        $self->pidl("}");
     return ($self->{res_hdr}, $self->{res});
old mode 100644 (file)
new mode 100755 (executable)
index 2f5be5f7915582977ad0bbed19a21c0aad04ea00..8d6ff56964cd40807f3a440cab83a240352a86ea 100644 (file)
@@ -5,7 +5,9 @@ FROM A FEW PEOPLE. DON'T TAKE THIS AS THE FINAL VERSION YET.
 
 
 Samba4 Programming Guide
-------------------------
+========================
+
+.. contents::
 
 The internals of Samba4 are quite different from previous versions of
 Samba, so even if you are an experienced Samba developer please take
@@ -144,8 +146,7 @@ data is a bug waiting to happen.
 Static data is evil as it has the following consequences:
 - it makes code much less likely to be thread-safe
 - it makes code much less likely to be recursion-safe
-- it leads to subtle side effects when the same code is called from
-  multiple places
+- it leads to subtle side effects when the same code is called from multiple places
 - doesn't play well with shared libraries or plugins
 
 Static data is particularly evil in library code (such as our internal
@@ -273,9 +274,9 @@ generating the right offsets.
 The same rule applies to strings. In many places in the SMB and MSRPC
 protocols complex strings are used on the wire, with complex rules
 about padding, format, alighment, termination etc. None of that
-information is useful to a high level calling routine or to a backend
-- its all just so much wire fluff. So, in Samba4 these strings are
-just "char *" and are always in our internal multi-byte format (which
+information is useful to a high level calling routine or to a backend - its 
+all just so much wire fluff. So, in Samba4 these strings are
+just "char \*" and are always in our internal multi-byte format (which
 is usually UTF8). It is up to the parse functions to worry about
 translating the format and getting the padding right.
 
@@ -580,13 +581,17 @@ DCERPC Handles
 The various handles that are used in the RPC servers should be created and 
 fetch using the dcesrv_handle_* functions.
 
-Use dcesrv_handle_new(struct dcesrv_connection *, uint8 handle_type) to obtain 
+Use dcesrv_handle_new(struct dcesrv_connection \*, uint8 handle_type) to obtain 
 a new handle of the specified type. Handle types are unique within each 
 pipe.
 
-The handle can later be fetched again using
-struct dcesrv_handle *dcesrv_handle_fetch(struct dcesrv_connection *dce_conn, struct policy_handle *p, uint8 handle_type)
-and destroyed by dcesrv_handle_destroy(struct dcesrv_handle *).
+The handle can later be fetched again using::
+
+       struct dcesrv_handle *dcesrv_handle_fetch(struct dcesrv_connection *dce_conn, struct policy_handle *p, uint8 handle_type)
+
+and destroyed by::
+
+       dcesrv_handle_destroy(struct dcesrv_handle *).
 
 User data should be stored in the 'data' member of the dcesrv_handle struct.
 
@@ -765,12 +770,10 @@ BUGS:
   no 137 resolution not possible
   should not fallback to anon when pass supplied
   should check pass-thu cap bit, and skip lots of tests
-  possibly allow the test suite to say "allow oversized replies" for
-     trans2 and other calls
+  possibly allow the test suite to say "allow oversized replies" for trans2 and other calls
   handle servers that don't have the setattre call in torture
   add max file coponent length test and max path len test
-  check for alloc failure in all core reply.c and trans2.c code where
-    allocation size depends on client parameter
+  check for alloc failure in all core reply.c and trans2.c code where allocation size depends on client parameter
 
 case-insenstive idea:
   all filenames on disk lowercase
index b8ce0523dd43422dc6759eb4425f050b6f96b365..09c054a1e3ba1ef5d1eeb730d6b7e2cb7b59edde 100644 (file)
@@ -127,6 +127,7 @@ LOGFILEBASE = @logfilebase@
 CONFIGFILE = $(CONFIGDIR)/smb.conf
 LMHOSTSFILE = $(CONFIGDIR)/lmhosts
 CTDBDIR = @ctdbdir@
+NCALRPCDIR = @ncalrpcdir@
 
 # This is where smbpasswd et al go
 PRIVATEDIR = @privatedir@
@@ -166,6 +167,7 @@ PATH_FLAGS = -DSMB_PASSWD_FILE=\"$(SMB_PASSWD_FILE)\" \
        -DLOGFILEBASE=\"$(LOGFILEBASE)\" \
        -DSHLIBEXT=\"@SHLIBEXT@\" \
        -DCTDBDIR=\"$(CTDBDIR)\" \
+       -DNCALRPCDIR=\"$(NCALRPCDIR)\" \
        -DCONFIGDIR=\"$(CONFIGDIR)\" \
        -DCODEPAGEDIR=\"$(CODEPAGEDIR)\" \
        -DCACHEDIR=\"$(CACHEDIR)\" \
@@ -621,6 +623,7 @@ VFS_FILEID_OBJ = modules/vfs_fileid.o
 VFS_AIO_FORK_OBJ = modules/vfs_aio_fork.o
 VFS_SYNCOPS_OBJ = modules/vfs_syncops.o
 VFS_ACL_XATTR_OBJ = modules/vfs_acl_xattr.o
+VFS_SMB_TRAFFIC_ANALYZER_OBJ = modules/vfs_smb_traffic_analyzer.o
 
 PLAINTEXT_AUTH_OBJ = auth/pampass.o auth/pass_check.o
 
@@ -635,6 +638,7 @@ AUTH_SERVER_OBJ = auth/auth_server.o
 AUTH_UNIX_OBJ = auth/auth_unix.o
 AUTH_WINBIND_OBJ = auth/auth_winbind.o
 AUTH_SCRIPT_OBJ = auth/auth_script.o
+AUTH_NETLOGOND_OBJ = auth/auth_netlogond.o
 
 AUTH_OBJ = auth/auth.o @AUTH_STATIC@ auth/auth_util.o auth/token_util.o \
           auth/auth_compat.o auth/auth_ntlmssp.o \
@@ -738,6 +742,10 @@ TESTPARM_OBJ = utils/testparm.o \
                $(PARAM_OBJ) $(LIB_NONSMBD_OBJ) $(POPT_LIB_OBJ) \
               $(LIBSAMBA_OBJ)
 
+TEST_LP_LOAD_OBJ = param/test_lp_load.o \
+                  $(PARAM_OBJ) $(LIB_NONSMBD_OBJ) \
+                  $(POPT_LIB_OBJ) $(LIBSAMBA_OBJ)
+
 PASSWD_UTIL_OBJ = utils/passwd_util.o
 
 SMBPASSWD_OBJ = utils/smbpasswd.o $(PASSWD_UTIL_OBJ) $(PASSCHANGE_OBJ) \
@@ -1070,7 +1078,7 @@ LDBDEL_OBJ = $(LDB_CMDLINE_OBJ) lib/ldb/tools/ldbdel.o
 LDBMODIFY_OBJ = $(LDB_CMDLINE_OBJ) lib/ldb/tools/ldbmodify.o
 
 WINBIND_KRB5_LOCATOR_OBJ1 = nsswitch/winbind_krb5_locator.o
-WINBIND_KRB5_LOCATOR_OBJ = $(WINBIND_KRB5_LOCATOR_OBJ1) $(WBCOMMON_OBJ) $(LIBREPLACE_OBJ)
+WINBIND_KRB5_LOCATOR_OBJ = $(WINBIND_KRB5_LOCATOR_OBJ1) $(LIBREPLACE_OBJ)
 
 POPT_OBJ=../lib/popt/findme.o ../lib/popt/popt.o ../lib/popt/poptconfig.o \
           ../lib/popt/popthelp.o ../lib/popt/poptparse.o
@@ -1138,6 +1146,8 @@ pam_smbpass: SHOWFLAGS bin/pam_smbpass.@SHLIBEXT@
 
 pam_winbind: SHOWFLAGS bin/pam_winbind.@SHLIBEXT@
 
+gpext_modules:: $(GPEXT_MODULES)
+
 torture:: SHOWFLAGS $(TORTURE_PROGS)
 
 smbtorture : SHOWFLAGS bin/smbtorture@EXEEXT@
@@ -1708,6 +1718,7 @@ LIBWBCLIENT_OBJ0 = nsswitch/libwbclient/wbclient.o \
                  nsswitch/libwbclient/wbc_pwd.o \
                  nsswitch/libwbclient/wbc_idmap.o \
                  nsswitch/libwbclient/wbc_sid.o \
+                 nsswitch/libwbclient/wbc_guid.o \
                  nsswitch/libwbclient/wbc_pam.o
 LIBWBCLIENT_OBJ = $(LIBWBCLIENT_OBJ0) \
                  $(WBCOMMON_OBJ) \
@@ -2166,15 +2177,15 @@ bin/vlp@EXEEXT@: $(BINARY_PREREQS) $(VLP_OBJ) @LIBTALLOC_SHARED@ @LIBTDB_SHARED@
                $(LDAP_LIBS) $(KRB5LIBS) $(LIBS) $(LIBTALLOC_LIBS) $(LIBTDB_LIBS) \
                @SONAMEFLAG@`basename $@`@NSSSONAMEVERSIONSUFFIX@
 
-bin/winbind_krb5_locator.@SHLIBEXT@: $(BINARY_PREREQS) $(WINBIND_KRB5_LOCATOR_OBJ)
+bin/winbind_krb5_locator.@SHLIBEXT@: $(BINARY_PREREQS) $(WINBIND_KRB5_LOCATOR_OBJ) @LIBWBCLIENT_SHARED@
        @echo "Linking $@"
-       @$(SHLD) $(LDSHFLAGS) -o $@ $(WINBIND_KRB5_LOCATOR_OBJ) \
+       @$(SHLD) $(LDSHFLAGS) -o $@ $(WINBIND_KRB5_LOCATOR_OBJ) $(WINBIND_LIBS) \
                @SONAMEFLAG@`basename $@`
 
-bin/pam_winbind.@SHLIBEXT@: $(BINARY_PREREQS) $(PAM_WINBIND_OBJ)
+bin/pam_winbind.@SHLIBEXT@: $(BINARY_PREREQS) $(PAM_WINBIND_OBJ) @LIBTALLOC_SHARED@ @LIBWBCLIENT_SHARED@
        @echo "Linking shared library $@"
        @$(SHLD) $(LDSHFLAGS) -o $@ $(PAM_WINBIND_OBJ) -lpam @INIPARSERLIBS@ \
-               $(PAM_WINBIND_EXTRA_LIBS) @SONAMEFLAG@`basename $@`
+               $(PAM_WINBIND_EXTRA_LIBS) $(LIBTALLOC_LIBS) $(WINBIND_LIBS) @SONAMEFLAG@`basename $@`
 
 bin/builtin.@SHLIBEXT@: $(BINARY_PREREQS) $(AUTH_BUILTIN_OBJ)
        @echo "Building plugin $@"
@@ -2188,6 +2199,10 @@ bin/script.@SHLIBEXT@: $(BINARY_PREREQS) $(AUTH_SCRIPT_OBJ)
        @echo "Building plugin $@"
        @$(SHLD_MODULE) $(AUTH_SCRIPT_OBJ)
 
+bin/netlogond.@SHLIBEXT@: $(BINARY_PREREQS) $(AUTH_NETLOGOND_OBJ)
+       @echo "Building plugin $@"
+       @$(SHLD_MODULE) $(AUTH_NETLOGOND_OBJ)
+
 bin/smbserver.@SHLIBEXT@: $(BINARY_PREREQS) $(AUTH_SERVER_OBJ)
        @echo "Building plugin $@"
        @$(SHLD_MODULE) $(AUTH_SERVER_OBJ)
@@ -2403,6 +2418,10 @@ bin/acl_xattr.@SHLIBEXT@: $(BINARY_PREREQS) $(VFS_ACL_XATTR_OBJ)
        @echo "Building plugin $@"
        @$(SHLD_MODULE) $(VFS_ACL_XATTR_OBJ)
 
+bin/smb_traffic_analyzer.@SHLIBEXT@: $(BINARY_PREREQS) $(VFS_SMB_TRAFFIC_ANALYZER_OBJ)
+       @echo "Building plugin $@"
+       @$(SHLD_MODULE) $(VFS_SMB_TRAFFIC_ANALYZER_OBJ)
+
 bin/registry.@SHLIBEXT@: $(BINARY_PREREQS) libgpo/gpext/registry.o
        @echo "Building plugin $@"
        @$(SHLD_MODULE) libgpo/gpext/registry.o
@@ -2411,6 +2430,10 @@ bin/scripts.@SHLIBEXT@: $(BINARY_PREREQS) libgpo/gpext/scripts.o
        @echo "Building plugin $@"
        @$(SHLD_MODULE) libgpo/gpext/scripts.o
 
+bin/security.@SHLIBEXT@: $(BINARY_PREREQS) libgpo/gpext/security.o
+       @echo "Building plugin $@"
+       @$(SHLD_MODULE) libgpo/gpext/security.o
+
 #########################################################
 ## IdMap NSS plugins
 
@@ -2483,6 +2506,13 @@ bin/rpc_open_tcp@EXEEXT@: $(BINARY_PREREQS) $(RPC_OPEN_TCP_OBJ) @LIBTALLOC_SHARE
                $(LIBS) $(LIBTALLOC_LIBS) @LIBTDB_SHARED@ $(WINBIND_LIBS) \
                $(LDAP_LIBS) $(KRB5LIBS) $(NSCD_LIBS)
 
+bin/test_lp_load@EXEEXT@: $(BINARY_PREREQS) $(TEST_LP_LOAD_OBJ) @BUILD_POPT@ @LIBTALLOC_SHARED@ @LIBTDB_SHARED@
+       @echo "Linking $@"
+       @$(CC) $(FLAGS) -o $@ $(TEST_LP_LOAD_OBJ) \
+               $(LDFLAGS) $(DYNEEXP) $(LIBS) \
+               $(LDAP_LIBS) \
+               $(POPT_LIBS) $(LIBTALLOC_LIBS) $(LIBTDB_LIBS)
+
 install:: installservers installbin @INSTALL_CIFSMOUNT@ @INSTALL_CIFSUPCALL@ installman \
                installscripts installdat installmodules @SWAT_INSTALL_TARGETS@ \
                @INSTALL_PAM_MODULES@ installlibs
@@ -2533,6 +2563,8 @@ installmodules:: modules installdirs
        @$(SHELL) $(srcdir)/script/linkmodules.sh $(DESTDIR)$(AUTHLIBDIR) domain.@SHLIBEXT@ trustdomain.@SHLIBEXT@ ntdomain.@SHLIBEXT@
        @$(SHELL) $(srcdir)/script/linkmodules.sh $(DESTDIR)$(AUTHLIBDIR) builtin.@SHLIBEXT@ guest.@SHLIBEXT@ fixed_challenge.@SHLIBEXT@ name_to_ntstatus.@SHLIBEXT@
        @$(SHELL) $(srcdir)/script/linkmodules.sh $(DESTDIR)$(NSSINFOLIBDIR) ../idmap/ad.@SHLIBEXT@ rfc2307.@SHLIBEXT@ sfu.@SHLIBEXT@ sfu20.@SHLIBEXT@
+       @$(SHELL) $(srcdir)/script/linkmodules.sh $(DESTDIR)$(NSSINFOLIBDIR) ../idmap/adex.@SHLIBEXT@ adex.@SHLIBEXT@
+       @$(SHELL) $(srcdir)/script/linkmodules.sh $(DESTDIR)$(NSSINFOLIBDIR) ../idmap/hash.@SHLIBEXT@ hash.@SHLIBEXT@
 
 installscripts:: installdirs
        @$(SHELL) $(srcdir)/script/installscripts.sh $(INSTALLPERMS_BIN) $(DESTDIR)$(BINDIR) $(SCRIPTS)
@@ -2628,6 +2660,10 @@ uninstallpammodules::
 # Toplevel clean files
 TOPFILES=dynconfig.o
 
+cleanlibs::
+       -rm -f ../lib/*/*.o ../lib/*/*/*.o \
+               ../libcli/*.o ../libcli/*/*.o
+
 clean:: cleanlibs
        -rm -f include/build_env.h
        -rm -f smbd/build_options.c
@@ -2738,6 +2774,10 @@ valgrindtest:: all torture timelimit
         VALGRIND="valgrind -q --num-callers=30 --log-file=${selftest_prefix}/valgrind.log" \
         PERL="$(PERL)" $(srcdir)/script/tests/selftest.sh ${selftest_prefix} all "${smbtorture4_path}"
 
+# Check for Winbind struct 32/64bit padding
+test_wbpad:
+       @echo "Testing winbind request/response structure for 32/64bit padding"
+       @./script/tests/wb_pad.sh || exit 1;
 
 ##
 ## Examples:
index c25e62ab809310a213789954014e674620c62ba4..f11dbe60ee13a41493c8f12f1599ea5163a6ecee 100644 (file)
 extern bool global_machine_password_needs_changing;
 static struct named_mutex *mutex;
 
+/*
+ * Change machine password (called from main loop
+ * idle timeout. Must be done as root.
+ */
+
+void attempt_machine_password_change(void)
+{
+       unsigned char trust_passwd_hash[16];
+       time_t lct;
+       void *lock;
+
+       if (!global_machine_password_needs_changing) {
+               return;
+       }
+
+       if (lp_security() != SEC_DOMAIN) {
+               return;
+       }
+
+       /*
+        * We're in domain level security, and the code that
+        * read the machine password flagged that the machine
+        * password needs changing.
+        */
+
+       /*
+        * First, open the machine password file with an exclusive lock.
+        */
+
+       lock = secrets_get_trust_account_lock(NULL, lp_workgroup());
+
+       if (lock == NULL) {
+               DEBUG(0,("attempt_machine_password_change: unable to lock "
+                       "the machine account password for machine %s in "
+                       "domain %s.\n",
+                       global_myname(), lp_workgroup() ));
+               return;
+       }
+
+       if(!secrets_fetch_trust_account_password(lp_workgroup(),
+                       trust_passwd_hash, &lct, NULL)) {
+               DEBUG(0,("attempt_machine_password_change: unable to read the "
+                       "machine account password for %s in domain %s.\n",
+                       global_myname(), lp_workgroup()));
+               TALLOC_FREE(lock);
+               return;
+       }
+
+       /*
+        * Make sure someone else hasn't already done this.
+        */
+
+       if(time(NULL) < lct + lp_machine_password_timeout()) {
+               global_machine_password_needs_changing = false;
+               TALLOC_FREE(lock);
+               return;
+       }
+
+       /* always just contact the PDC here */
+
+       change_trust_account_password( lp_workgroup(), NULL);
+       global_machine_password_needs_changing = false;
+       TALLOC_FREE(lock);
+}
+
 /**
  * Connect to a remote server for (inter)domain security authenticaion.
  *
diff --git a/source3/auth/auth_netlogond.c b/source3/auth/auth_netlogond.c
new file mode 100644 (file)
index 0000000..a57f3b7
--- /dev/null
@@ -0,0 +1,321 @@
+/*
+   Unix SMB/CIFS implementation.
+   Authenticate against a netlogon pipe listening on a unix domain socket
+   Copyright (C) Volker Lendecke 2008
+
+   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"
+
+#undef DBGC_CLASS
+#define DBGC_CLASS DBGC_AUTH
+
+static NTSTATUS netlogond_validate(TALLOC_CTX *mem_ctx,
+                                  const struct auth_context *auth_context,
+                                  const char *ncalrpc_sockname,
+                                  uint8_t schannel_key[16],
+                                  const auth_usersupplied_info *user_info,
+                                  struct netr_SamInfo3 **pinfo3,
+                                  NTSTATUS *schannel_bind_result)
+{
+       struct rpc_pipe_client *p;
+       struct cli_pipe_auth_data *auth;
+       struct netr_SamInfo3 *info3 = NULL;
+       NTSTATUS status;
+
+       *schannel_bind_result = NT_STATUS_OK;
+
+       status = rpc_pipe_open_ncalrpc(talloc_tos(), ncalrpc_sockname,
+                                      &ndr_table_netlogon.syntax_id, &p);
+       if (!NT_STATUS_IS_OK(status)) {
+               DEBUG(10, ("rpc_pipe_open_ncalrpc failed: %s\n",
+                          nt_errstr(status)));
+               return status;
+       }
+
+       status = rpccli_schannel_bind_data(p, lp_workgroup(),
+                                          PIPE_AUTH_LEVEL_PRIVACY,
+                                          schannel_key, &auth);
+       if (!NT_STATUS_IS_OK(status)) {
+               DEBUG(10, ("rpccli_schannel_bind_data failed: %s\n",
+                          nt_errstr(status)));
+               TALLOC_FREE(p);
+               return status;
+       }
+
+       status = rpc_pipe_bind(p, auth);
+       if (!NT_STATUS_IS_OK(status)) {
+               DEBUG(10, ("rpc_pipe_bind failed: %s\n", nt_errstr(status)));
+               TALLOC_FREE(p);
+               *schannel_bind_result = status;
+               return status;
+       }
+
+       /*
+        * We have to fake a struct dcinfo, so that
+        * rpccli_netlogon_sam_network_logon_ex can decrypt the session keys.
+        */
+
+       p->dc = talloc(p, struct dcinfo);
+       if (p->dc == NULL) {
+               DEBUG(0, ("talloc failed\n"));
+               TALLOC_FREE(p);
+               return NT_STATUS_NO_MEMORY;
+       }
+
+       memcpy(p->dc->sess_key, schannel_key, 16);
+
+       status = rpccli_netlogon_sam_network_logon_ex(
+               p, p,
+               user_info->logon_parameters,/* flags such as 'allow
+                                            * workstation logon' */
+               global_myname(),            /* server name */
+               user_info->smb_name,        /* user name logging on. */
+               user_info->client_domain,   /* domain name */
+               user_info->wksta_name,      /* workstation name */
+               (uchar *)auth_context->challenge.data, /* 8 byte challenge. */
+               user_info->lm_resp,         /* lanman 24 byte response */
+               user_info->nt_resp,         /* nt 24 byte response */
+               &info3);                    /* info3 out */
+
+       DEBUG(10, ("rpccli_netlogon_sam_network_logon_ex returned %s\n",
+                  nt_errstr(status)));
+
+       if (!NT_STATUS_IS_OK(status)) {
+               TALLOC_FREE(p);
+               return status;
+       }
+
+       *pinfo3 = talloc_move(mem_ctx, &info3);
+
+       TALLOC_FREE(p);
+       return NT_STATUS_OK;
+}
+
+static char *mymachinepw(TALLOC_CTX *mem_ctx)
+{
+       fstring pwd;
+       const char *script;
+       char *to_free = NULL;
+       ssize_t nread;
+       int ret, fd;
+
+       script = lp_parm_const_string(
+               GLOBAL_SECTION_SNUM, "auth_netlogond", "machinepwscript",
+               NULL);
+
+       if (script == NULL) {
+               to_free = talloc_asprintf(talloc_tos(), "%s/%s",
+                                         get_dyn_SBINDIR(), "mymachinepw");
+               script = to_free;
+       }
+       if (script == NULL) {
+               return NULL;
+       }
+
+       ret = smbrun(script, &fd);
+       DEBUG(ret ? 0 : 3, ("mymachinepw: Running the command `%s' gave %d\n",
+                           script, ret));
+       TALLOC_FREE(to_free);
+
+       if (ret != 0) {
+               return NULL;
+       }
+
+       pwd[sizeof(pwd)-1] = '\0';
+
+       nread = read(fd, pwd, sizeof(pwd)-1);
+       close(fd);
+
+       if (nread <= 0) {
+               DEBUG(3, ("mymachinepwd: Could not read password\n"));
+               return NULL;
+       }
+
+       DEBUG(0, ("pwd: %d [%s]\n", (int)nread, pwd));
+
+       if (pwd[nread-1] == '\n') {
+               pwd[nread-1] = '\0';
+       }
+
+       return talloc_strdup(mem_ctx, pwd);
+}
+
+static NTSTATUS check_netlogond_security(const struct auth_context *auth_context,
+                                        void *my_private_data,
+                                        TALLOC_CTX *mem_ctx,
+                                        const auth_usersupplied_info *user_info,
+                                        auth_serversupplied_info **server_info)
+{
+       TALLOC_CTX *frame = talloc_stackframe();
+       struct netr_SamInfo3 *info3 = NULL;
+       struct rpc_pipe_client *p;
+       struct cli_pipe_auth_data *auth;
+       uint32_t neg_flags = NETLOGON_NEG_AUTH2_ADS_FLAGS;
+       char *plaintext_machinepw;
+       uint8_t machine_password[16];
+       uint8_t schannel_key[16];
+       NTSTATUS schannel_bind_result, status;
+       struct named_mutex *mutex;
+       const char *ncalrpcsock;
+
+       ncalrpcsock = lp_parm_const_string(
+               GLOBAL_SECTION_SNUM, "auth_netlogond", "socket", NULL);
+
+       if (ncalrpcsock == NULL) {
+               ncalrpcsock = talloc_asprintf(talloc_tos(), "%s/%s",
+                                             get_dyn_NCALRPCDIR(), "DEFAULT");
+       }
+
+       if (ncalrpcsock == NULL) {
+               status = NT_STATUS_NO_MEMORY;
+               goto done;
+       }
+
+       if (!secrets_fetch_local_schannel_key(schannel_key)) {
+               goto new_key;
+       }
+
+       status = netlogond_validate(talloc_tos(), auth_context, ncalrpcsock,
+                                   schannel_key, user_info, &info3,
+                                   &schannel_bind_result);
+
+       DEBUG(10, ("netlogond_validate returned %s\n", nt_errstr(status)));
+
+       if (NT_STATUS_IS_OK(status)) {
+               goto okay;
+       }
+
+       if (NT_STATUS_IS_OK(schannel_bind_result)) {
+               /*
+                * This is a real failure from the DC
+                */
+               goto done;
+       }
+
+ new_key:
+
+       mutex = grab_named_mutex(talloc_tos(), "LOCAL_SCHANNEL_KEY", 60);
+       if (mutex == NULL) {
+               DEBUG(10, ("Could not get mutex LOCAL_SCHANNEL_KEY\n"));
+               status = NT_STATUS_ACCESS_DENIED;
+               goto done;
+       }
+
+       DEBUG(10, ("schannel bind failed, setting up new key\n"));
+
+       status = rpc_pipe_open_ncalrpc(talloc_tos(), ncalrpcsock,
+                                      &ndr_table_netlogon.syntax_id, &p);
+
+       if (!NT_STATUS_IS_OK(status)) {
+               DEBUG(10, ("rpc_pipe_open_ncalrpc failed: %s\n",
+                          nt_errstr(status)));
+               goto done;
+       }
+
+       status = rpccli_anon_bind_data(p, &auth);
+       if (!NT_STATUS_IS_OK(status)) {
+               DEBUG(10, ("rpccli_anon_bind_data failed: %s\n",
+                          nt_errstr(status)));
+               goto done;
+       }
+
+       status = rpc_pipe_bind(p, auth);
+       if (!NT_STATUS_IS_OK(status)) {
+               DEBUG(10, ("rpc_pipe_bind failed: %s\n", nt_errstr(status)));
+               goto done;
+       }
+
+       TALLOC_FREE(auth);
+
+       plaintext_machinepw = mymachinepw(talloc_tos());
+       if (plaintext_machinepw == NULL) {
+               status = NT_STATUS_NO_MEMORY;
+               goto done;
+       }
+
+       E_md4hash(plaintext_machinepw, machine_password);
+
+       TALLOC_FREE(plaintext_machinepw);
+
+       status = rpccli_netlogon_setup_creds(
+               p, global_myname(), lp_workgroup(), global_myname(),
+               global_myname(), machine_password, SEC_CHAN_BDC, &neg_flags);
+
+       if (!NT_STATUS_IS_OK(status)) {
+               DEBUG(10, ("rpccli_netlogon_setup_creds failed: %s\n",
+                          nt_errstr(status)));
+               goto done;
+       }
+
+       memcpy(schannel_key, p->dc->sess_key, 16);
+       secrets_store_local_schannel_key(schannel_key);
+
+       TALLOC_FREE(p);
+
+       /*
+        * Retry the authentication with the mutex held. This way nobody else
+        * can step on our toes.
+        */
+
+       status = netlogond_validate(talloc_tos(), auth_context, ncalrpcsock,
+                                   schannel_key, user_info, &info3,
+                                   &schannel_bind_result);
+
+       DEBUG(10, ("netlogond_validate returned %s\n", nt_errstr(status)));
+
+       if (!NT_STATUS_IS_OK(status)) {
+               goto done;
+       }
+
+ okay:
+
+       status = make_server_info_info3(mem_ctx, user_info->smb_name,
+                                       user_info->domain, server_info,
+                                       info3);
+       if (!NT_STATUS_IS_OK(status)) {
+               DEBUG(10, ("make_server_info_info3 failed: %s\n",
+                          nt_errstr(status)));
+               TALLOC_FREE(frame);
+               return status;
+       }
+
+       status = NT_STATUS_OK;
+
+ done:
+       TALLOC_FREE(frame);
+       return status;
+}
+
+/* module initialisation */
+static NTSTATUS auth_init_netlogond(struct auth_context *auth_context,
+                                   const char *param,
+                                   auth_methods **auth_method)
+{
+       if (!make_auth_methods(auth_context, auth_method)) {
+               return NT_STATUS_NO_MEMORY;
+       }
+
+       (*auth_method)->name = "netlogond";
+       (*auth_method)->auth = check_netlogond_security;
+       return NT_STATUS_OK;
+}
+
+NTSTATUS auth_netlogond_init(void)
+{
+       smb_register_auth(AUTH_INTERFACE_VERSION, "netlogond",
+                         auth_init_netlogond);
+       return NT_STATUS_OK;
+}
index deed774b39eec0cc815024192c041875c74f0101..61316a8f70cd8c22bda7d6a3badf14200ff1bbe3 100755 (executable)
@@ -2,6 +2,18 @@
 
 # Run this script to build samba from GIT.
 
+while true; do
+    case $1 in
+       (--version-file)
+           VERSION_FILE=$2
+           shift 2
+           ;;
+       (*)
+           break
+           ;;
+    esac
+done
+
 ## insert all possible names (only works with 
 ## autoconf 2.x)
 TESTAUTOHEADER="autoheader autoheader-2.53 autoheader2.50 autoheader259 autoheader253"
@@ -48,7 +60,7 @@ if test "$AUTOCONFFOUND" = "0" -o "$AUTOHEADERFOUND" = "0"; then
 fi
 
 echo "$0: running script/mkversion.sh"
-./script/mkversion.sh || exit 1
+./script/mkversion.sh $VERSION_FILE || exit 1
 
 rm -rf autom4te*.cache
 rm -f configure include/config.h*
index 7af7d301084018a0438f03fe4bac03dddb8c8321..eb9f31bdf2736a436206f6d0aebadbcaae16ca08 100644 (file)
@@ -4345,6 +4345,8 @@ cleanup:
        }
 }
 
+static bool finished;
+
 /****************************************************************************
  Make sure we swallow keepalives during idle time.
 ****************************************************************************/
@@ -4391,6 +4393,8 @@ static void readline_callback(void)
                        DEBUG(0, ("Read from server failed, maybe it closed "
                                  "the connection\n"));
 
+                       finished = true;
+                       smb_readline_done();
                        if (NT_STATUS_EQUAL(status, NT_STATUS_END_OF_FILE)) {
                                set_smb_read_error(&cli->smb_rw_error,
                                                   SMB_READ_EOF);
@@ -4417,9 +4421,17 @@ static void readline_callback(void)
 
        /* Ping the server to keep the connection alive using SMBecho. */
        {
+               NTSTATUS status;
                unsigned char garbage[16];
                memset(garbage, 0xf0, sizeof(garbage));
-               cli_echo(cli, 1, data_blob_const(garbage, sizeof(garbage)));
+               status = cli_echo(cli, 1, data_blob_const(garbage, sizeof(garbage)));
+
+               if (!NT_STATUS_IS_OK(status)) {
+                       DEBUG(0, ("SMBecho failed. Maybe server has closed "
+                               "the connection\n"));
+                       finished = true;
+                       smb_readline_done();
+               }
        }
 }
 
@@ -4431,7 +4443,7 @@ static int process_stdin(void)
 {
        int rc = 0;
 
-       while (1) {
+       while (!finished) {
                TALLOC_CTX *frame = talloc_stackframe();
                char *tok = NULL;
                char *the_prompt = NULL;
index b7a76c61024abfd37651659e0ab34ec924b8d886..fd8014cf9ff7c5248cb955a7f02b9d9c32bce7c3 100644 (file)
 #define MOUNT_PASSWD_SIZE 64
 #define DOMAIN_SIZE 64
 
+/* exit status - bits below are ORed */
+#define EX_USAGE        1       /* incorrect invocation or permission */
+#define EX_SYSERR       2       /* out of memory, cannot fork, ... */
+#define EX_SOFTWARE     4       /* internal mount bug or wrong version */
+#define EX_USER         8       /* user interrupt */
+#define EX_FILEIO      16       /* problems writing, locking, ... mtab/fstab */
+#define EX_FAIL        32       /* mount failure */
+#define EX_SOMEOK      64       /* some mount succeeded */
+
 const char *thisprogram;
 int verboseflag = 0;
 static int got_password = 0;
@@ -174,7 +183,7 @@ static void mount_cifs_usage(void)
        printf("\n\t%s -V\n",thisprogram);
 
        SAFE_FREE(mountpassword);
-       exit(1);
+       exit(EX_USAGE);
 }
 
 /* caller frees username if necessary */
@@ -233,7 +242,7 @@ static int open_cred_file(char * file_name)
                                if(length > 4086) {
                                        printf("mount.cifs failed due to malformed username in credentials file");
                                        memset(line_buf,0,4096);
-                                       exit(1);
+                                       exit(EX_USAGE);
                                } else {
                                        got_user = 1;
                                        user_name = (char *)calloc(1 + length,1);
@@ -257,7 +266,7 @@ static int open_cred_file(char * file_name)
                                if(length > MOUNT_PASSWD_SIZE) {
                                        printf("mount.cifs failed: password in credentials file too long\n");
                                        memset(line_buf,0, 4096);
-                                       exit(1);
+                                       exit(EX_USAGE);
                                } else {
                                        if(mountpassword == NULL) {
                                                mountpassword = (char *)calloc(MOUNT_PASSWD_SIZE+1,1);
@@ -285,7 +294,7 @@ static int open_cred_file(char * file_name)
                                 }
                                 if(length > DOMAIN_SIZE) {
                                         printf("mount.cifs failed: domain in credentials file too long\n");
-                                        exit(1);
+                                        exit(EX_USAGE);
                                 } else {
                                         if(domain_name == NULL) {
                                                 domain_name = (char *)calloc(DOMAIN_SIZE+1,1);
@@ -318,7 +327,7 @@ static int get_password_from_file(int file_descript, char * filename)
 
        if (mountpassword == NULL) {
                printf("malloc failed\n");
-               exit(1);
+               exit(EX_SYSERR);
        }
 
        if(filename != NULL) {
@@ -326,7 +335,7 @@ static int get_password_from_file(int file_descript, char * filename)
                if(file_descript < 0) {
                        printf("mount.cifs failed. %s attempting to open password file %s\n",
                                   strerror(errno),filename);
-                       exit(1);
+                       exit(EX_SYSERR);
                }
        }
        /* else file already open and fd provided */
@@ -337,7 +346,7 @@ static int get_password_from_file(int file_descript, char * filename)
                        printf("mount.cifs failed. Error %s reading password file\n",strerror(errno));
                        if(filename != NULL)
                                close(file_descript);
-                       exit(1);
+                       exit(EX_SYSERR);
                } else if(rc == 0) {
                        if(mountpassword[0] == 0) {
                                if(verboseflag)
@@ -563,7 +572,7 @@ static int parse_options(char ** optionsp, int * filesys_flags)
 
                                        if (!(pw = getpwnam(value))) {
                                                printf("bad user name \"%s\"\n", value);
-                                               exit(1);
+                                               exit(EX_USAGE);
                                        }
                                        snprintf(user, sizeof(user), "%u", pw->pw_uid);
                                } else {
@@ -579,7 +588,7 @@ static int parse_options(char ** optionsp, int * filesys_flags)
 
                                        if (!(gr = getgrnam(value))) {
                                                printf("bad group name \"%s\"\n", value);
-                                               exit(1);
+                                               exit(EX_USAGE);
                                        }
                                        snprintf(group, sizeof(group), "%u", gr->gr_gid);
                                } else {
@@ -674,7 +683,7 @@ static int parse_options(char ** optionsp, int * filesys_flags)
                out = (char *)realloc(out, out_len + word_len + 2);
                if (out == NULL) {
                        perror("malloc");
-                       exit(1);
+                       exit(EX_SYSERR);
                }
 
                if (out_len) {
@@ -699,7 +708,7 @@ nocopy:
                out = (char *)realloc(out, out_len + word_len + 6);
                if (out == NULL) {
                        perror("malloc");
-                       exit(1);
+                       exit(EX_SYSERR);
                }
 
                if (out_len) {
@@ -715,7 +724,7 @@ nocopy:
                out = (char *)realloc(out, out_len + 1 + word_len + 6);
                if (out == NULL) {
                perror("malloc");
-                       exit(1);
+                       exit(EX_SYSERR);
                }
 
                if (out_len) {
@@ -996,12 +1005,12 @@ static struct option longopts[] = {
 };
 
 /* convert a string to uppercase. return false if the string
- * wasn't ASCII or was a NULL ptr */
+ * wasn't ASCII. Return success on a NULL ptr */
 static int
 uppercase_string(char *string)
 {
        if (!string)
-               return 0;
+               return 1;
 
        while (*string) {
                /* check for unicode */
@@ -1050,7 +1059,7 @@ int main(int argc, char ** argv)
                thisprogram = argv[0];
        } else {
                mount_cifs_usage();
-               exit(1);
+               exit(EX_USAGE);
        }
 
        if(thisprogram == NULL)
@@ -1067,12 +1076,12 @@ int main(int argc, char ** argv)
                share_name = strndup(argv[1], MAX_UNC_LEN);
                if (share_name == NULL) {
                        fprintf(stderr, "%s: %s", argv[0], strerror(ENOMEM));
-                       exit(1);
+                       exit(EX_SYSERR);
                }
                mountpoint = argv[2];
        } else {
                mount_cifs_usage();
-               exit(1);
+               exit(EX_USAGE);
        }
 
        /* add sharename in opts string as unc= parm */
@@ -1094,7 +1103,7 @@ int main(int argc, char ** argv)
                case '?':
                case 'h':        /* help */
                        mount_cifs_usage ();
-                       exit(1);
+                       exit(EX_USAGE);
                case 'n':
                    ++nomtab;
                    break;
@@ -1148,14 +1157,14 @@ int main(int argc, char ** argv)
                                uid = strtoul(optarg, &ep, 10);
                                if (*ep) {
                                        printf("bad uid value \"%s\"\n", optarg);
-                                       exit(1);
+                                       exit(EX_USAGE);
                                }
                        } else {
                                struct passwd *pw;
 
                                if (!(pw = getpwnam(optarg))) {
                                        printf("bad user name \"%s\"\n", optarg);
-                                       exit(1);
+                                       exit(EX_USAGE);
                                }
                                uid = pw->pw_uid;
                                endpwent();
@@ -1168,14 +1177,14 @@ int main(int argc, char ** argv)
                                gid = strtoul(optarg, &ep, 10);
                                if (*ep) {
                                        printf("bad gid value \"%s\"\n", optarg);
-                                       exit(1);
+                                       exit(EX_USAGE);
                                }
                        } else {
                                struct group *gr;
 
                                if (!(gr = getgrnam(optarg))) {
                                        printf("bad user name \"%s\"\n", optarg);
-                                       exit(1);
+                                       exit(EX_USAGE);
                                }
                                gid = gr->gr_gid;
                                endpwent();
@@ -1205,13 +1214,13 @@ int main(int argc, char ** argv)
                default:
                        printf("unknown mount option %c\n",c);
                        mount_cifs_usage();
-                       exit(1);
+                       exit(EX_USAGE);
                }
        }
 
        if((argc < 3) || (dev_name == NULL) || (mountpoint == NULL)) {
                mount_cifs_usage();
-               exit(1);
+               exit(EX_USAGE);
        }
 
        if (getenv("PASSWD")) {
@@ -1228,13 +1237,13 @@ int main(int argc, char ** argv)
        }
 
         if (orgoptions && parse_options(&orgoptions, &flags)) {
-                rc = -1;
+                rc = EX_USAGE;
                goto mount_exit;
        }
        ipaddr = parse_server(&share_name);
        if((ipaddr == NULL) && (got_ip == 0)) {
                printf("No ip address specified and hostname not found\n");
-               rc = -1;
+               rc = EX_USAGE;
                goto mount_exit;
        }
        
@@ -1249,19 +1258,19 @@ int main(int argc, char ** argv)
        }
        if(chdir(mountpoint)) {
                printf("mount error: can not change directory into mount target %s\n",mountpoint);
-               rc = -1;
+               rc = EX_USAGE;
                goto mount_exit;
        }
 
        if(stat (".", &statbuf)) {
                printf("mount error: mount point %s does not exist\n",mountpoint);
-               rc = -1;
+               rc = EX_USAGE;
                goto mount_exit;
        }
 
        if (S_ISDIR(statbuf.st_mode) == 0) {
                printf("mount error: mount point %s is not a directory\n",mountpoint);
-               rc = -1;
+               rc = EX_USAGE;
                goto mount_exit;
        }
 
@@ -1274,7 +1283,7 @@ int main(int argc, char ** argv)
 #endif                                         
                } else {
                        printf("mount error: permission denied or not superuser and mount.cifs not installed SUID\n"); 
-                       return -1;
+                       exit(EX_USAGE);
                }
        }
 
@@ -1289,7 +1298,7 @@ int main(int argc, char ** argv)
                mountpassword = (char *)calloc(MOUNT_PASSWD_SIZE+1,1);
                if (!tmp_pass || !mountpassword) {
                        printf("Password not entered, exiting\n");
-                       return -1;
+                       exit(EX_USAGE);
                }
                strlcpy(mountpassword, tmp_pass, MOUNT_PASSWD_SIZE+1);
                got_password = 1;
@@ -1307,7 +1316,7 @@ mount_retry:
        else {
                printf("No server share name specified\n");
                printf("\nMounting the DFS root for server not implemented yet\n");
-                exit(1);
+                exit(EX_USAGE);
        }
        if(user_name)
                optlen += strlen(user_name) + 6;
@@ -1321,7 +1330,7 @@ mount_retry:
 
        if(options == NULL) {
                printf("Could not allocate memory for mount options\n");
-               return -1;
+               exit(EX_SYSERR);
        }
 
        options[0] = 0;
@@ -1400,8 +1409,7 @@ mount_retry:
                        printf("mount error %d = %s\n",errno,strerror(errno));
                }
                printf("Refer to the mount.cifs(8) manual page (e.g.man mount.cifs)\n");
-               rc = -1;
-               goto mount_exit;
+               rc = EX_FAIL;
        } else {
                pmntfile = setmntent(MOUNTED, "a+");
                if(pmntfile) {
@@ -1439,11 +1447,13 @@ mount_retry:
                        rc = addmntent(pmntfile,&mountent);
                        endmntent(pmntfile);
                        SAFE_FREE(mountent.mnt_opts);
+                       if (rc)
+                               rc = EX_FILEIO;
                } else {
-                   printf("could not update mount table\n");
+                       printf("could not update mount table\n");
+                       rc = EX_FILEIO;
                }
        }
-       rc = 0;
 mount_exit:
        if(mountpassword) {
                int len = strlen(mountpassword);
@@ -1455,5 +1465,5 @@ mount_exit:
        SAFE_FREE(orgoptions);
        SAFE_FREE(resolved_path);
        SAFE_FREE(share_name);
-       return rc;
+       exit(rc);
 }
index f23f6b55be304b36ecbaad3075d69c0c01b3ccfd..1eba4a0a58122fc5ee1477926daa3a0e7fac2a9a 100644 (file)
@@ -128,7 +128,7 @@ fi
 if test "x$debug" = "xyes" ; then
        CFLAGS="${CFLAGS} -g"
 else
-       CFLAGS="-O"
+       CFLAGS="${CFLAGS} -O"
 fi
 
 m4_include(../lib/socket_wrapper/config.m4)
@@ -404,10 +404,10 @@ AC_SUBST(DYNEXP)
 
 dnl Add modules that have to be built by default here
 dnl These have to be built static:
-default_static_modules="pdb_smbpasswd pdb_tdbsam rpc_lsarpc rpc_samr rpc_winreg rpc_initshutdown rpc_dssetup rpc_wkssvc rpc_svcctl2 rpc_ntsvcs2 rpc_netlogon rpc_netdfs rpc_srvsvc rpc_spoolss rpc_eventlog2 auth_sam auth_unix auth_winbind auth_server auth_domain auth_builtin vfs_default nss_info_template"
+default_static_modules="pdb_smbpasswd pdb_tdbsam rpc_lsarpc rpc_samr rpc_winreg rpc_initshutdown rpc_dssetup rpc_wkssvc rpc_svcctl2 rpc_ntsvcs2 rpc_netlogon rpc_netdfs rpc_srvsvc rpc_spoolss rpc_eventlog2 auth_sam auth_unix auth_winbind auth_server auth_domain auth_builtin auth_netlogond vfs_default nss_info_template"
 
 dnl These are preferably build shared, and static if dlopen() is not available
-default_shared_modules="vfs_recycle vfs_audit vfs_extd_audit vfs_full_audit vfs_netatalk vfs_fake_perms vfs_default_quota vfs_readonly vfs_cap vfs_expand_msdfs vfs_shadow_copy vfs_shadow_copy2 charset_CP850 charset_CP437 auth_script vfs_readahead vfs_xattr_tdb vfs_streams_xattr vfs_acl_xattr"
+default_shared_modules="vfs_recycle vfs_audit vfs_extd_audit vfs_full_audit vfs_netatalk vfs_fake_perms vfs_default_quota vfs_readonly vfs_cap vfs_expand_msdfs vfs_shadow_copy vfs_shadow_copy2 charset_CP850 charset_CP437 auth_script vfs_readahead vfs_xattr_tdb vfs_streams_xattr vfs_acl_xattr vfs_smb_traffic_analyzer"
 
 if test "x$developer" = xyes; then
    default_static_modules="$default_static_modules rpc_rpcecho"
@@ -6077,6 +6077,7 @@ SMB_MODULE(auth_server, \$(AUTH_SERVER_OBJ), "bin/smbserver.$SHLIBEXT", AUTH)
 SMB_MODULE(auth_domain, \$(AUTH_DOMAIN_OBJ), "bin/domain.$SHLIBEXT", AUTH)
 SMB_MODULE(auth_builtin, \$(AUTH_BUILTIN_OBJ), "bin/builtin.$SHLIBEXT", AUTH)
 SMB_MODULE(auth_script, \$(AUTH_SCRIPT_OBJ), "bin/script.$SHLIBEXT", AUTH)
+SMB_MODULE(auth_netlogond, \$(AUTH_NETLOGOND_OBJ), "bin/netlogond.$SHLIBEXT", AUTH)
 SMB_SUBSYSTEM(AUTH,auth/auth.o)
 
 SMB_MODULE(vfs_default, \$(VFS_DEFAULT_OBJ), "bin/default.$SHLIBEXT", VFS)
@@ -6116,12 +6117,13 @@ SMB_MODULE(vfs_syncops, \$(VFS_SYNCOPS_OBJ), "bin/syncops.$SHLIBEXT", VFS)
 SMB_MODULE(vfs_zfsacl, \$(VFS_ZFSACL_OBJ), "bin/zfsacl.$SHLIBEXT", VFS)
 SMB_MODULE(vfs_notify_fam, \$(VFS_NOTIFY_FAM_OBJ), "bin/notify_fam.$SHLIBEXT", VFS)
 SMB_MODULE(vfs_acl_xattr, \$(VFS_ACL_XATTR_OBJ), "bin/acl_xattr.$SHLIBEXT", VFS)
-
+SMB_MODULE(vfs_smb_traffic_analyzer, \$(VFS_SMB_TRAFFIC_ANALYZER_OBJ), "bin/smb_traffic_analyzer.$SHLIBEXT", VFS)
 
 SMB_SUBSYSTEM(VFS,smbd/vfs.o)
 
 SMB_MODULE(gpext_registry, libgpo/gpext/registry.o, "bin/registry.$SHLIBEXT", GPEXT)
 SMB_MODULE(gpext_scripts, libgpo/gpext/scripts.o, "bin/scripts.$SHLIBEXT", GPEXT)
+SMB_MODULE(gpext_security, libgpo/gpext/security.o, "bin/security.$SHLIBEXT", GPEXT)
 SMB_SUBSYSTEM(GPEXT, libgpo/gpext/gpext.o)
 
 AC_DEFINE_UNQUOTED(STRING_STATIC_MODULES, "$string_static_modules", [String list of builtin modules])
@@ -6276,6 +6278,10 @@ CFLAGS="${CFLAGS} \$(FLAGS)"
 
 if test x$MERGED_BUILD != x1; then
        CFLAGS="${CFLAGS} -D_SAMBA_BUILD_=3"
+else
+       if test x"$BLDSHARED" = x"true" ; then
+               LDFLAGS="$LDFLAGS -L./bin"
+       fi
 fi
 
 AC_OUTPUT(Makefile
index 3a54507599323ce2fc02dcd815f72f8d7465e23a..6125f9944cab01fb760598a8897ac909542a0a73 100644 (file)
@@ -77,6 +77,7 @@ DEFINE_DYN_CONFIG_PARAM(MODULESDIR)
 DEFINE_DYN_CONFIG_PARAM(SHLIBEXT)
 DEFINE_DYN_CONFIG_PARAM(LOCKDIR)
 DEFINE_DYN_CONFIG_PARAM(PIDDIR)
+DEFINE_DYN_CONFIG_PARAM(NCALRPCDIR)
 DEFINE_DYN_CONFIG_PARAM(SMB_PASSWD_FILE)
 DEFINE_DYN_CONFIG_PARAM(PRIVATE_DIR)
 
index 7cee53a9689cebdb261cb548464b5398b8c72e26..29927eb592b7230a6a4617fb11d94e041d7d66e9 100644 (file)
@@ -666,8 +666,7 @@ static NTSTATUS del_aliasmem(const DOM_SID *alias, const DOM_SID *member)
 
        if (num == 0) {
                status = dbwrap_delete_bystring(db, key);
-               TALLOC_FREE(sids);
-               goto cancel;
+               goto commit;
        }
 
        member_string = talloc_strdup(sids, "");
@@ -693,7 +692,7 @@ static NTSTATUS del_aliasmem(const DOM_SID *alias, const DOM_SID *member)
 
        status = dbwrap_store_bystring(
                db, key, string_term_tdb_data(member_string), 0);
-
+ commit:
        TALLOC_FREE(sids);
 
        if (!NT_STATUS_IS_OK(status)) {
index 758bde33cc5279b0a3625c54f039d7311f512205..8267064f23ee5d232cadf76420ed56ce235cc6f8 100644 (file)
@@ -71,6 +71,10 @@ const char *get_dyn_PIDDIR(void);
 const char *set_dyn_PIDDIR(const char *newpath);
 bool is_default_dyn_PIDDIR(void);
 
+const char *get_dyn_NCALRPCDIR(void);
+const char *set_dyn_NCALRPCDIR(const char *newpath);
+bool is_default_dyn_NCALRPCDIR(void);
+
 const char *get_dyn_SMB_PASSWD_FILE(void);
 const char *set_dyn_SMB_PASSWD_FILE(const char *newpath);
 bool is_default_dyn_SMB_PASSWD_FILE(void);
diff --git a/source3/include/libmsrpc.h b/source3/include/libmsrpc.h
deleted file mode 100644 (file)
index 3f2a726..0000000
+++ /dev/null
@@ -1,3045 +0,0 @@
-/* 
- *  Unix SMB/CIFS implementation.
- *  MS-RPC client library API definitions/prototypes
- *
- *  Copyright (C) Chris Nicholls              2005.
- *  
- *  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/>.
- */
-
-#ifndef LIBMSRPC_H
-#define LIBMSRPC_H
-
-
-#include "includes.h"
-#include "libsmbclient.h"
-#include "libsmb_internal.h"
-
-/*server capability levels*/
-#define SRV_WIN_NT4     1
-#define SRV_WIN_2K      2
-#define SRV_WIN_2K_SP3  3
-#define SRV_WIN_2K3     4
-
-/**@defgroup handle Server Handle*/
-/**@defgroup Library_Functions Library/Utility Functions*/
-/**@defgroup lsa_defs LSA Definitions*/
-/**@defgroup LSA_Functions LSA Functions*/
-/**@defgroup reg_defs Registry Definitions*/
-/**@defgroup Reg_Functions Registry Functions*/
-/**@defgroup sam_defs SAM Definitions*/
-/**@defgroup SAM_Functions SAM Functions*/
-/**@defgroup svc_defs Service Control Definitions*/
-/**@defgroup SCM_Functions Service Control Functions*/
-
-/**Operation was unsuccessful*/
-#define CAC_FAILURE           0
-/**Operation was successful*/
-#define CAC_SUCCESS           1
-/**Operation was only partially successful
- *  an example of this is if you try to lookup a list of accounts to SIDs and not all accounts can be resolved*/
-#define CAC_PARTIAL_SUCCESS   2
-
-/**@ingroup CAC_errors Use this to see if the last operation failed - useful for enumeration functions that use multiple calls*/
-#define CAC_OP_FAILED(status) !NT_STATUS_IS_OK(status) && \
-                              NT_STATUS_V(status) != NT_STATUS_V(STATUS_SOME_UNMAPPED) && \
-                              NT_STATUS_V(status) != NT_STATUS_V(STATUS_NO_MORE_FILES) && \
-                              NT_STATUS_V(status) != NT_STATUS_V(NT_STATUS_NO_MORE_ENTRIES) && \
-                              NT_STATUS_V(status) != NT_STATUS_V(NT_STATUS_NONE_MAPPED) && \
-                              NT_STATUS_V(status) != NT_STATUS_V(NT_STATUS_GUIDS_EXHAUSTED)
-
-
-/**Privilege string constants*/
-#define CAC_SE_CREATE_TOKEN            "SeCreateTokenPrivilege"
-#define CAC_SE_ASSIGN_PRIMARY_TOKEN    "SeAssignPrimaryTokenPrivilege"
-#define CAC_SE_LOCK_MEMORY             "SeLockMemoryPrivilege"
-#define CAC_SE_INCREASE_QUOTA          "SeIncreaseQuotaPrivilege"
-#define CAC_SE_MACHINE_ACCOUNT         "SeMachineAccountPrivilege"
-#define CAC_SE_TCB                     "SeTcbPrivilege"
-#define CAC_SE_SECURITY                "SeSecurityPrivilege"
-#define CAC_SE_TAKE_OWNERSHIP          "SeTakeOwnershipPrivilege"
-#define CAC_SE_LOAD_DRIVER             "SeLoadDriverPrivilege"
-#define CAC_SE_SYSTEM_PROFILE          "SeSystemProfilePrivilege"
-#define CAC_SE_SYSTEM_TIME             "SeSystemtimePrivilege"
-#define CAC_SE_PROFILE_SINGLE_PROC     "SeProfileSingleProcessPrivilege"
-#define CAC_SE_INCREASE_BASE_PRIORITY  "SeIncreaseBasePriorityPrivilege"
-#define CAC_SE_CREATE_PAGEFILE         "SeCreatePagefilePrivilege"
-#define CAC_SE_CREATE_PERMANENT        "SeCreatePermanentPrivilege"
-#define CAC_SE_BACKUP                  "SeBackupPrivilege"
-#define CAC_SE_RESTORE                 "SeRestorePrivilege"
-#define CAC_SE_SHUTDOWN                "SeShutdownPrivilege"
-#define CAC_SE_DEBUG                   "SeDebugPrivilege"
-#define CAC_SE_AUDIT                   "SeAuditPrivilege"
-#define CAC_SE_SYSTEM_ENV              "SeSystemEnvironmentPrivilege"
-#define CAC_SE_CHANGE_NOTIFY           "SeChangeNotifyPrivilege"
-#define CAC_SE_REMOTE_SHUTDOWN         "SeRemoteShutdownPrivilege"
-#define CAC_SE_UNDOCK                  "SeUndockPrivilege"
-#define CAC_SE_SYNC_AGENT              "SeSyncAgentPrivilege"
-#define CAC_SE_ENABLE_DELEGATION       "SeEnableDelegationPrivilege"
-#define CAC_SE_MANAGE_VOLUME           "SeManageVolumePrivilege"
-#define CAC_SE_IMPERSONATE             "SeImpersonatePrivilege"
-#define CAC_SE_CREATE_GLOBAL           "SeCreateGlobalPrivilege"
-#define CAC_SE_PRINT_OPERATOR          "SePrintOperatorPrivilege"
-#define CAC_SE_NETWORK_LOGON           "SeNetworkLogonRight"
-#define CAC_SE_INTERACTIVE_LOGON       "SeInteractiveLogonRight"
-#define CAC_SE_BATCH_LOGON             "SeBatchLogonRight"
-#define CAC_SE_SERVICE_LOGON           "SeServiceLogonRight"
-#define CAC_SE_ADD_USERS               "SeAddUsersPrivilege"
-#define CAC_SE_DISK_OPERATOR           "SeDiskOperatorPrivilege"
-
-/**
- * @addtogroup lsa_defs
- * @{
- */
-/**used to specify what data to retrieve using cac_LsaQueryTrustedDomainInformation*/
-#define CAC_INFO_TRUSTED_DOMAIN_NAME         0x1
-#define CAC_INFO_TRUSTED_DOMAIN_POSIX_OFFSET 0x3
-#define CAC_INFO_TRUSTED_DOMAIN_PASSWORD     0x4
-
-/**Used when requesting machine domain information*/
-#define CAC_DOMAIN_INFO 0x0003
-
-/**Used when requesting machine local information*/
-#define CAC_LOCAL_INFO  0x0005
-
-/**Stores information about a SID*/
-typedef struct _CACSIDINFO {
-   /**The actual SID*/
-   DOM_SID sid;
-   
-   /**The name of the object which maps to this SID*/
-   char *name;
-
-   /**The domain the SID belongs to*/
-   char *domain;
-} CacSidInfo;
-/* @} */
-
-/**
- * @addtogroup reg_defs
- * @{
- */
-/**Null terminated string*/
-typedef char*  REG_SZ_DATA;
-
-/**Null terminated string with windows environment variables that should be expanded*/
-typedef char*  REG_EXPAND_SZ_DATA;
-
-/**Binary data of some kind*/
-typedef struct _REGBINARYDATA {
-   uint32 data_length;
-   uint8 * data;
-} REG_BINARY_DATA;
-   
-/**32-bit (little endian) number*/
-typedef uint32 REG_DWORD_DATA;
-
-/**32-bit big endian number*/
-typedef uint32 REG_DWORD_BE_DATA;
-
-/**array of strings*/
-typedef struct _REGMULTISZDATA {
-   uint32 num_strings;
-
-   char **strings;
-} REG_MULTI_SZ_DATA;
-
-typedef union _REGVALUEDATA {
-   REG_SZ_DATA          reg_sz;
-   REG_EXPAND_SZ_DATA   reg_expand_sz;
-   REG_BINARY_DATA      reg_binary;
-   REG_DWORD_DATA       reg_dword;
-   REG_DWORD_BE_DATA    reg_dword_be;
-   REG_MULTI_SZ_DATA    reg_multi_sz;
-} REG_VALUE_DATA;
-/**@}*/
-
-/**
- * @addtogroup sam_defs
- * @{
- */
-
-#define CAC_USER_RID  0x1
-#define CAC_GROUP_RID 0x2
-
-typedef struct _CACLOOKUPRIDSRECORD {
-   char *name;
-   uint32 rid;
-
-   /**If found, this will be one of:
-    * - CAC_USER_RID
-    * - CAC_GROUP_RID
-    */
-   uint32 type;
-   
-   /*if the name or RID was looked up, then found = True*/
-   bool found;
-} CacLookupRidsRecord;
-
-typedef struct _CACUSERINFO {
-   /**Last logon time*/
-   time_t logon_time;
-
-   /**Last logoff time*/
-   time_t logoff_time;
-
-   /**Last kickoff time*/
-   time_t kickoff_time;
-
-   /**Last password set time*/
-   time_t pass_last_set_time;
-
-   /**Time password can change*/
-   time_t pass_can_change_time;
-
-   /**Time password must change*/
-   time_t pass_must_change_time;
-
-   /**LM user password*/
-   uint8 lm_password[8];
-
-   /**NT user password*/
-   uint8 nt_password[8];
-
-   /**User's RID*/
-   uint32 rid;
-
-   /**RID of primary group*/
-   uint32 group_rid;
-
-   /**User's ACB mask*/
-   uint32 acb_mask;
-
-   /**Bad password count*/
-   uint16 bad_passwd_count;
-
-   /**Number of logons*/
-   uint16 logon_count;
-
-   /**Change password at next logon?*/
-   bool pass_must_change;
-
-   /**Username*/
-   char *username;
-
-   /**User's full name*/
-   char *full_name;
-
-   /**User's home directory*/
-   char *home_dir;
-
-   /**Home directory drive*/
-   char *home_drive;
-
-   /**Logon script*/
-   char *logon_script;
-
-   /**Path to profile*/
-   char *profile_path;
-
-   /**Account description*/
-   char *description;
-
-   /**Login from workstations*/
-   char *workstations;
-
-   char *dial;
-
-   /**Possible logon hours*/
-   LOGON_HRS *logon_hours;
-
-} CacUserInfo;
-
-typedef struct _CACGROUPINFO {
-   /**Group name*/
-   char *name;
-
-   /**Description*/
-   char *description;
-   /**Number of members*/
-   uint32 num_members;
-} CacGroupInfo, CacAliasInfo;
-
-/**Represents a period (duration) of time*/
-typedef struct _CACTIME {
-   /**Number of days*/
-   uint32 days;
-
-   /**Number of hours*/
-   uint32 hours;
-
-   /**Number of minutes*/
-   uint32 minutes;
-
-   /**number of seconds*/
-   uint32 seconds;
-} CacTime;
-
-
-typedef struct _CACDOMINFO {
-   /**The server role. Should be one of:
-    *   ROLE_STANDALONE
-    *   ROLE_DOMAIN_MEMBER
-    *   ROLE_DOMAIN_BDC
-    *   ROLE_DOMAIN_PDC
-    *   see include/smb.h
-    */
-   uint32 server_role;
-
-   /**Number of domain users*/
-   uint32 num_users;
-
-   /**Number of domain groups*/
-   uint32 num_domain_groups;
-   
-   /**Number of local groups*/
-   uint32 num_local_groups;
-
-   /**Comment*/
-   char *comment;
-
-   /**Domain name*/
-   char *domain_name;
-
-   /**Server name*/
-   char *server_name;
-
-   /**Minimum password length*/
-   uint16 min_pass_length;
-
-   /**How many previous passwords to remember - ie, password cannot be the same as N previous passwords*/
-   uint16 pass_history;
-
-   /**How long (from now) before passwords expire*/
-   CacTime expire;
-
-   /**How long (from now) before passwords can be changed*/
-   CacTime min_pass_age;
-
-   /**How long users are locked out for too many bad password attempts*/
-   CacTime lockout_duration;
-
-   /**How long before lockouts are reset*/
-   CacTime lockout_reset;
-
-   /**How many bad password attempts before lockout occurs*/
-   uint16 num_bad_attempts;
-} CacDomainInfo;
-
-/**@}*/ /*sam_defs*/
-
-/**@addtogroup svc_defs
- * @{
- */
-typedef struct _CACSERVICE {
-   /**The service name*/
-   char *service_name;
-
-   /**The display name of the service*/
-   char *display_name;
-   
-   /**Current status of the service - see include/rpc_svcctl.h for SERVICE_STATUS definition*/
-   SERVICE_STATUS status;
-} CacService;
-
-typedef struct __CACSERVICECONFIG {
-   /**The service type*/
-   uint32 type;
-
-   /**The start type. Should be one of:
-    * - SVCCTL_BOOT_START
-    * - SVCCTL_SYSTEM_START
-    * - SVCCTL_AUTO_START
-    * - SVCCTL_DEMAND_START
-    */
-   uint32 start_type;
-
-   uint32 error_control;
-
-   /**Path to executable*/
-   char *exe_path;
-
-   /***/
-   char *load_order_group;
-
-   uint32 tag_id;
-
-   /**Any dependencies for the service*/
-   char *dependencies;
-
-   /**Run as...*/
-   char *start_name;
-
-   /**Service display name*/
-   char *display_name;
-   
-} CacServiceConfig;
-/**@}*/ /*svc_defs*/
-
-#include "libmsrpc_internal.h"
-
-/**
- * @addtogroup handle
- * @{
- */
-
-/**
- * Server handle used to keep track of client/server/pipe information. Use cac_NewServerHandle() to allocate. 
- * Initiliaze as many values as possible before calling cac_Connect(). 
- * 
- * @note When allocating memory for the fields, use SMB_MALLOC() (or equivalent) instead of talloc() (or equivalent) -  
- * If memory is not allocated for a field, cac_Connect will allocate sizeof(fstring) bytes for it.
- * 
- * @note It may be wise to allocate large buffers for these fields and strcpy data into them.
- *
- * @see cac_NewServerHandle()
- * @see cac_FreeHandle()
- */
-typedef struct _CACSERVERHANDLE {
-   /** debug level
-    */
-   int debug;
-
-   /** netbios name used to make connections
-    */
-   char *netbios_name;
-
-   /** domain name used to make connections
-    */
-   char *domain;
-
-   /** username used to make connections
-    */
-   char *username;
-
-   /** user's password plain text string
-    */
-   char *password;
-
-   /** name or IP address of server we are currently working with
-    */
-   char *server;
-
-   /**stores the latest NTSTATUS code
-    */
-   NTSTATUS status;
-   
-   /** internal. do not modify!
-    */
-   struct CacServerHandleInternal _internal;
-
-} CacServerHandle;
-
-/*@}*/
-
-/**internal function. do not call this function*/
-SMBCSRV *cac_GetServer(CacServerHandle *hnd);
-
-
-/** @addtogroup Library_Functions
- * @{
- */
-/**
- * Initializes the library - do not need to call this function.  Open's smb.conf as well as initializes logging.
- * @param debug Debug level for library to use
- */
-
-void cac_Init(int debug);
-
-/**
- * Creates an un-initialized CacServerHandle
- * @param allocate_fields If True, the function will allocate sizeof(fstring) bytes for all char * fields in the handle
- * @return - un-initialized server handle
- *         - NULL if no memory could be allocated
- */
-CacServerHandle * cac_NewServerHandle(bool allocate_fields);
-
-/**
- * Specifies the smbc_get_auth_data_fn to use if you do not want to use the default.
- * @param hnd non-NULL server handle
- * @param auth_fn  auth_data_fn to set in server handle
- */
-
-void cac_SetAuthDataFn(CacServerHandle *hnd, smbc_get_auth_data_fn auth_fn);
-
-/** Use your own libsmbclient context - not necessary. 
- * @note You must still call cac_Connect() after specifying your own libsmbclient context
- * @param hnd Initialized, but not connected CacServerHandle
- * @param ctx The libsmbclient context you would like to use.
- */
-void cac_SetSmbcContext(CacServerHandle *hnd, SMBCCTX *ctx);
-
-/** Connects to a specified server.  If there is already a connection to a different server, 
- *    it will be cleaned up before connecting to the new server.
- * @param hnd   Pre-initialized CacServerHandle
- * @param srv   (Optional) Name or IP of the server to connect to.  If NULL, server from the CacServerHandle will be used.
- *
- * @return CAC_FAILURE if the operation could not be completed successfully (hnd->status will also be set with a NTSTATUS code)
- * @return CAC_SUCCESS if the operation succeeded
- */            
-int cac_Connect(CacServerHandle *hnd, const char *srv);
-
-
-/**
- * Cleans up any data used by the CacServerHandle. If the libsmbclient context was set using cac_SetSmbcContext(), it will not be free'd. 
- * @param hnd the CacServerHandle to destroy
- */
-void cac_FreeHandle(CacServerHandle * hnd);
-
-/**
- * Initializes a CacTime structure based on an NTTIME structure
- *  If the function fails, then the CacTime structure will be zero'd out
- */
-void cac_InitCacTime(CacTime *cactime, NTTIME nttime);
-
-/**
- * Called by cac_NewServerHandle() if allocate_fields = True. You can call this if you want to, allocates sizeof(fstring) char's for every char * field
- * @param hnd Uninitialized server handle
- * @return CAC_FAILURE Memory could not be allocated
- * @return CAC_SUCCESS Memory was allocated
- */
-int cac_InitHandleMem(CacServerHandle *hnd);
-
-/**
- * Default smbc_get_auth_data_fn for libmsrpc. This function is called when libmsrpc needs to get more information about the 
- * client (username/password, workgroup). 
- * This function provides simple prompts to the user to enter the information. This description his here so you know how to re-define this function.
- * @see cac_SetAuthDataFn()
- * @param pServer Name/IP of the server to connect to. 
- * @param pShare Share name to connect to
- * @param pWorkgroup libmsrpc passes in the workgroup/domain name from hnd->domain. It can be modified in the function.
- * @param maxLenWorkgroup The maximum length of a string pWogroup can hold.
- * @param pUsername libmsrpc passes in the username from hnd->username. It can be modified in the function.
- * @param maxLenUsername The maximum length of a string pUsername can hold.
- * @param pPassword libmsrpc pass in the password from hnd->password. It can be modified in the function.
- * @param maxLenPassword The maximum length  of a string pPassword can hold.
- */
-void cac_GetAuthDataFn(const char * pServer,
-                 const char * pShare,
-                 char * pWorkgroup,
-                 int maxLenWorkgroup,
-                 char * pUsername,
-                 int maxLenUsername,
-                 char * pPassword,
-                 int maxLenPassword);
-
-
-/**@}*/
-
-/*****************
- * LSA Functions *
- *****************/
-
-/** @addtogroup LSA_Functions
- * @{
- */
-
-struct LsaOpenPolicy {
-   /**Inputs*/
-   struct {
-      /**Access Mask. Refer to Security Access Masks in include/rpc_secdes.h*/
-      uint32 access;
-
-      /**Use security quality of service? (True/False)*/
-      bool security_qos;
-   } in;
-
-   /**Outputs*/
-   struct {
-      /**Handle to the open policy (needed for all other operations)*/
-      POLICY_HND *pol;
-   } out;
-};
-
-/** 
- * Opens a policy handle on a remote machine.
- * @param hnd fully initialized CacServerHandle for remote machine
- * @param mem_ctx Talloc context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE if the policy could not be opened. hnd->status set with appropriate NTSTATUS
- * @return CAC_SUCCESS if the policy could be opened, the policy handle can be found
- */
-int cac_LsaOpenPolicy(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct LsaOpenPolicy *op);
-
-
-/** 
- * Closes an  LSA policy handle (Retrieved using cac_LsaOpenPolicy).
- *   If successful, the handle will be closed on the server, and memory for pol will be freed
- * @param hnd - An initialized and connected server handle
- * @param mem_ctx Talloc context for memory allocation
- * @param pol - the policy handle to close
- * @return CAC_FAILURE could not close the policy handle, hnd->status is set to the appropriate NTSTATUS error code
- * @return CAC_SUCCESS the policy handle was closed 
- */
-int cac_LsaClosePolicy(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, POLICY_HND *pol);
-
-
-struct LsaGetNamesFromSids {
-   struct {
-      /**handle to and open LSA policy*/
-      POLICY_HND *pol;
-      
-      /**the number of SIDs to lookup*/
-      uint32 num_sids;
-      
-      /**array of SIDs to lookup*/
-      DOM_SID *sids;
-   } in;
-
-   struct {
-      /**The number of names returned (in case of CAC_PARTIAL_SUCCESS)*/
-      uint32 num_found;
-
-      /**array of SID info each index is one sid */
-      CacSidInfo *sids;
-
-      /**in case of partial success, an array of SIDs that could not be looked up (NULL if all sids were looked up)*/
-      DOM_SID *unknown;
-   } out;
-};
-
-/** 
- * Looks up the names for a list of SIDS
- * @param hnd initialized and connected server handle
- * @param mem_ctx Talloc context for memory allocation
- * @param op  input and output parameters 
- * @return CAC_FAILURE none of the SIDs could be looked up hnd->status is set with appropriate NTSTATUS error code
- * @return CAC_SUCCESS all of the SIDs were translated and a list of names has been output
- * @return CAC_PARTIAL_SUCCESS not all of the SIDs were translated, as a result the number of returned names is less than the original list of SIDs
- */
-int cac_LsaGetNamesFromSids(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct LsaGetNamesFromSids *op);
-
-struct LsaGetSidsFromNames {
-   struct {
-      /**handle to an open LSA policy*/
-      POLICY_HND *pol;
-
-      /**number of SIDs to lookup*/
-      uint32 num_names;
-
-      /**array of strings listing the names*/
-      char **names;
-   } in;
-
-   struct {
-      /**The number of SIDs returned (in case of partial success*/
-      uint32 num_found;
-
-      /**array of SID info for the looked up names*/
-      CacSidInfo *sids;
-
-      /**in case of partial success, the names that were not looked up*/
-      char **unknown;
-   } out;
-};
-
-/** 
- * Looks up the SIDs for a list of names
- * @param hnd initialized and connected server handle
- * @param mem_ctx Talloc context for memory allocation
- * @param op  input and output parameters 
- * @return CAC_FAILURE none of the SIDs could be looked up hnd->status is set with appropriate NTSTATUS error code
- * @return CAC_SUCCESS all of the SIDs were translated and a list of names has been output
- * @return CAC_PARTIAL_SUCCESS not all of the SIDs were translated, as a result the number of returned names is less than the original list of SIDs
- */
-int cac_LsaGetSidsFromNames(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct LsaGetSidsFromNames *op);
-
-struct LsaFetchSid {
-   struct {
-      /**handle to an open LSA policy*/
-      POLICY_HND *pol;
-
-      /**can be CAC_LOCAL_INFO, CAC_DOMAIN_INFO, or (CAC_LOCAL_INFO | CAC_DOMAIN_INFO)*/
-      uint16 info_class;
-   } in;
-
-   struct {
-      /**the machine's local SID and domain name (NULL if not asked for)*/
-      CacSidInfo *local_sid;
-
-      /**the machine's domain SID and name (NULL if not asked for)*/
-      CacSidInfo *domain_sid;
-      
-   } out;
-};
-
-/** 
- * Looks up the domain or local sid of a machine with an open LSA policy handle
- * @param hnd initialized and connected server handle
- * @param mem_ctx Talloc context for memory allocation
- * @param op input and output parameters
- * @return CAC_FAILURE if the SID could not be fetched
- * @return CAC_SUCCESS if the SID was fetched
- * @return CAC_PARTIAL_SUCCESS if you asked for both local and domain sids but only one was returned
- */
-int cac_LsaFetchSid(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct LsaFetchSid *op);
-
-struct LsaQueryInfoPolicy {
-   struct {
-      /**Open LSA policy handle on remote server*/
-      POLICY_HND *pol;
-   } in;
-
-   struct {
-      /**remote server's domain name*/
-      char *domain_name;
-
-      /**remote server's dns name*/
-      char *dns_name;
-
-      /**remote server's forest name*/
-      char *forest_name;
-
-      /**remote server's domain guid*/
-      struct GUID *domain_guid;
-
-      /**remote server's domain SID*/
-      DOM_SID *domain_sid;
-   } out;
-};
-
-/** 
- * Retrieves information about the LSA machine/domain
- * @param hnd initialized and connected server handle
- * @param mem_ctx Talloc context for memory allocation
- * @param op input and output parameters
- *           Note: for pre-Windows 2000 machines, only op->out.SID and op->out.domain will be set. @see cac_LsaFetchSid
- * @return - CAC_FAILURE if the operation was not successful. hnd->status will be set with an accurate NT_STATUS code
- * @return CAC_SUCCESS the operation was successful.
- */
-int cac_LsaQueryInfoPolicy(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct LsaQueryInfoPolicy *op);
-
-struct LsaEnumSids {
-   struct {
-      /**Open LSA Policy handle*/
-      POLICY_HND *pol;
-
-      /**The prefered maximum number of SIDs returned per call*/
-      uint32 pref_max_sids;
-   } in;
-
-   struct {
-      /**used to keep track of how many sids have been retrieved over multiple calls
-       *  should be set to zero via ZERO_STRUCT() befrore the first call. Use the same struct LsaEnumSids for multiple calls*/
-      uint32 resume_idx;
-
-      /**The number of sids returned this call*/
-      uint32 num_sids;
-
-      /**Array of sids returned*/
-      DOM_SID *sids;
-
-   } out;
-};
-
-/** 
- * Enumerates the SIDs in the LSA.  Can be enumerated in blocks by calling the function multiple times.
- *  Example: while(cac_LsaEnumSids(hnd, mem_ctx, op) { ... }
- * @param hnd - An initialized and connected server handle
- * @param mem_ctx Talloc context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE there was an error during operations OR there are no more results
- * @return CAC_SUCCESS the operation completed and results were returned
- */
-int cac_LsaEnumSids(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct LsaEnumSids *op);
-
-struct LsaEnumAccountRights {
-   struct {
-      /**Open LSA Policy handle*/
-      POLICY_HND *pol;
-
-      /**(Optional) SID of the account - must supply either sid or name*/
-      DOM_SID *sid;
-
-      /**(Optional) name of the account - must supply either sid or name*/
-      char *name;
-   } in;
-
-   struct {
-      /**Count of rights for this account*/
-      uint32 num_privs;
-
-      /**array of privilege names*/
-      char **priv_names;
-   } out;
-};
-
-/** 
- * Enumerates rights assigned to a given account. Takes a SID instead of account handle as input
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized Parameters
- * @return CAC_FAILURE the rights could not be retrieved. hnd->status is set with NT_STATUS code
- * @return CAC_SUCCESS the operation was successful. 
- */
-
-int cac_LsaEnumAccountRights(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct LsaEnumAccountRights *op);
-
-struct LsaEnumTrustedDomains {
-   struct {
-      /**Open LSA policy handle*/
-      POLICY_HND *pol;
-   } in;
-
-   struct {
-      /**used to keep track of how many domains have been retrieved over multiple calls
-       *  should be set to zero via ZERO_STRUCT() before the first call. Use the same struct LsaEnumSids for multiple calls*/
-      uint32 resume_idx;
-      
-      /**The number of domains returned by the remote server this call*/
-      uint32 num_domains;
-
-      /**array of trusted domain names returned by the remote server*/
-      char **domain_names;
-
-      /**array of trusted domain sids returned by the remote server*/
-      DOM_SID *domain_sids;
-   } out;
-};
-     
-/** 
- * Enumerates the trusted domains in the LSA.  
- * @param hnd - An initialized and connected server handle
- * @param mem_ctx Talloc context for memory allocation
- * @param op - initialized parameters
- * @return CAC_FAILURE there was an error during operations OR there are no more results
- * @return CAC_SUCCESS the operation completed and results were returned
- */
-int cac_LsaEnumTrustedDomains(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct LsaEnumTrustedDomains *op);
-
-struct LsaOpenTrustedDomain {
-   struct {
-      /**an open LSA policy handle*/
-      POLICY_HND *pol;
-
-      /**SID of the trusted domain to open*/
-      DOM_SID *domain_sid;
-
-      /**Desired access on the open domain*/
-      uint32 access;
-   } in;
-
-   struct {
-      /**A handle to the policy that is opened*/
-      POLICY_HND *domain_pol;
-   } out;
-};
-
-/** 
- * Opens a trusted domain by SID.
- * @param hnd An initialized and connected server handle
- * @param mem_ctx Talloc context for memory allocation
- * @param op initialized I/O parameters
- * @return CAC_FAILURE a handle to the domain could not be opened. hnd->status is set with approriate NT_STATUS code
- * @return CAC_SUCCESS the domain was opened successfully
- */
-int cac_LsaOpenTrustedDomain(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct LsaOpenTrustedDomain *op);
-
-struct LsaQueryTrustedDomainInfo {
-   struct {
-      /**Open LSA policy handle*/
-      POLICY_HND *pol;
-
-      /**Info class of returned data*/
-      uint16 info_class;
-
-      /**(Optional)SID of trusted domain to query (must specify either SID or name of trusted domain)*/
-      DOM_SID *domain_sid;
-
-      /**(Optional)Name of trusted domain to query (must specify either SID or name of trusted domain)*/
-      char *domain_name;
-   } in;
-
-   struct {
-      /**information about the trusted domain*/
-      LSA_TRUSTED_DOMAIN_INFO *info;
-   } out;
-};
-
-/** 
- * Retrieves information a trusted domain.
- * @param hnd An initialized and connected server handle
- * @param mem_ctx Talloc context for memory allocation
- * @param op initialized I/O parameters
- * @return CAC_FAILURE a handle to the domain could not be opened. hnd->status is set with approriate NT_STATUS code
- * @return CAC_SUCCESS the domain was opened successfully
- */
-
-int cac_LsaQueryTrustedDomainInfo(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct LsaQueryTrustedDomainInfo *op);
-
-struct LsaEnumPrivileges {
-   struct {
-      /**An open LSA policy handle*/
-      POLICY_HND *pol;
-
-      /**The _preferred_ maxinum number of privileges returned per call*/
-      uint32 pref_max_privs;
-   } in;
-
-   struct {
-      /**Used to keep track of how many privileges have been retrieved over multiple calls. Do not modify this value between calls*/
-      uint32 resume_idx;
-
-      /**The number of privileges returned this call*/
-      uint32 num_privs;
-
-      /**Array of privilege names*/
-      char **priv_names;
-
-      /**Array of high bits for privilege LUID*/
-      uint32 *high_bits;
-
-      /**Array of low bits for privilege LUID*/
-      uint32 *low_bits;
-   } out; 
-};
-
-/** 
- * Enumerates the Privileges supported by the LSA.  Can be enumerated in blocks by calling the function multiple times.
- *  Example: while(cac_LsaEnumPrivileges(hnd, mem_ctx, op) { ... }
- * @param hnd An initialized and connected server handle
- * @param mem_ctx Talloc context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE there was an error during operations OR there are no more results
- * @return CAC_SUCCESS the operation completed and results were returned
- * @see CAC_OP_FAILED()
- */
-int cac_LsaEnumPrivileges(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct LsaEnumPrivileges *op);
-
-struct LsaOpenAccount {
-   struct {
-      /**An open LSA policy handle*/
-      POLICY_HND *pol;
-
-      /**(Optional) account SID - must supply either sid or name*/
-      DOM_SID *sid;
-
-      /**(Optional) account name - must supply either sid or name*/
-      char *name;
-
-      /**desired access for the handle*/
-      uint32 access;
-   } in;
-
-   struct {
-      /**A handle to the opened user*/
-      POLICY_HND *user;
-   } out;
-};
-
-/** 
- * Opens a handle to an account in the LSA
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized Parameters
- * @return CAC_FAILURE the account could not be opened. hnd->status has appropriate NT_STATUS code
- * @return CAC_SUCCESS the account was opened
- */
-int cac_LsaOpenAccount(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct LsaOpenAccount *op);
-
-struct LsaAddPrivileges {
-   struct {
-      /**An open LSA policy handle*/
-      POLICY_HND *pol;
-
-      /**(Optional) The user's SID (must specify at least sid or name)*/
-      DOM_SID *sid;
-
-      /**(Optional) The user's name (must specify at least sid or name)*/
-      char *name;
-
-      /**The privilege names of the privileges to add for the account*/
-      char **priv_names;
-      
-      /**The number of privileges in the priv_names array*/
-      uint32 num_privs;
-
-   } in;
-};
-
-/** 
- * Adds Privileges an account.
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized Parameters
- * @return CAC_FAILURE the privileges could not be set. hnd->status has appropriate NT_STATUS code
- * @return CAC_SUCCESS the privileges were set.
- */
-int cac_LsaAddPrivileges(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct LsaAddPrivileges *op);
-
-struct LsaRemovePrivileges {
-   struct {
-      /**An open handle to the LSA*/
-      POLICY_HND *pol;
-
-      /**(Optional) The account SID (must specify at least sid or name)*/
-      DOM_SID *sid;
-
-      /**(Optional) The account name (must specify at least sid or name)*/
-      char *name;
-
-      /**The privilege names of the privileges to remove from the account*/
-      char **priv_names;
-
-      /**The number of privileges in the priv_names array*/
-      uint32 num_privs;
-
-   } in;
-
-};
-
-/** 
- * Removes a _specific_ set of privileges from an account
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized Parameters
- * @return CAC_FAILURE the privileges could not be removed. hnd->status is set with NT_STATUS code
- * @return CAC_SUCCESS the privileges were removed 
- */
-int cac_LsaRemovePrivileges(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct LsaRemovePrivileges *op);
-
-struct LsaClearPrivileges {
-   struct {
-      /**An open handle to the LSA*/
-      POLICY_HND *pol;
-
-      /**(Optional) The user's SID (must specify at least sid or name)*/
-      DOM_SID *sid;
-
-      /**(Optional) The user's name (must specify at least sid or name)*/
-      char *name;
-   } in;
-
-};
-
-/** 
- * Removes ALL privileges from an account
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized Parameters
- * @return CAC_FAILURE the operation was not successful, hnd->status set with NT_STATUS code
- * @return CAC_SUCCESS the opeartion was successful.
- */
-int cac_LsaClearPrivileges(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct LsaClearPrivileges *op);
-
-/** 
- * Sets an accounts priviliges. Removes all privileges and then adds specified privileges.
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized Parameters 
- * @return CAC_FAILURE The operation could not complete successfully
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_LsaSetPrivileges(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct LsaAddPrivileges *op);
-
-struct LsaGetSecurityObject {
-   struct {
-      /**Open LSA policy handle*/
-      POLICY_HND *pol;
-   } in;
-
-   struct {
-      /**Returned security descriptor information*/
-      SEC_DESC_BUF *sec;
-   } out;
-};
-
-/**
- * Retrieves Security Descriptor information about the LSA
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized Parameters 
- * @return CAC_FAILURE The operation could not complete successfully
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_LsaGetSecurityObject(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct LsaGetSecurityObject *op);
-
-
-/**@}*/ /*LSA_Functions*/
-      
-/**********************
- * Registry Functions *
- *********************/
-
-/**@addtogroup Reg_Functions
- * @{
- */
-
-struct RegConnect {
-   struct {
-      /** must be one of : 
-       *    HKEY_CLASSES_ROOT, 
-       *    HKEY_LOCAL_MACHINE, 
-       *    HKEY_USERS, 
-       *    HKEY_PERFORMANCE_DATA,
-       */
-      int root;
-
-      /**desired access on the root key
-       * combination of: 
-       * REG_KEY_READ,
-       * REG_KEY_WRITE,
-       * REG_KEY_EXECUTE,
-       * REG_KEY_ALL,
-       * found in include/rpc_secdes.h*/
-      uint32 access;
-   } in;
-
-   struct {
-      POLICY_HND *key;
-   } out;
-};
-
-/** 
- * Opens a handle to the registry on the server
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized Parameters 
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_RegConnect(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct RegConnect *op);
-
-/**
- * Closes an open registry handle
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param key The Key/Handle to close 
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_RegClose(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, POLICY_HND *key);
-
-struct RegOpenKey {
-   struct {
-      /**(Optional)parent key. 
-       * If this is NULL, then cac_RegOpenKey() will attempt to connect to the registry, name MUST start with something like:<br>
-       *  HKEY_LOCAL_MACHINE\  or an abbreviation like HKCR\
-       *
-       *  supported root names:
-       *   - HKEY_LOCAL_MACHINE\ or HKLM\
-       *   - HKEY_CLASSES_ROOT\ or HKCR\
-       *   - HKEY_USERS\ or HKU\
-       *   - HKEY_PERFORMANCE_DATA or HKPD\
-       */
-      POLICY_HND *parent_key;
-
-      /**name/path of key*/
-      char *name;
-
-      /**desired access on this key*/
-      uint32 access;
-   } in;
-
-   struct {
-      POLICY_HND *key;
-   } out;
-};
-      
-/**
- * Opens a registry key
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-
-int cac_RegOpenKey(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct RegOpenKey *op);
-
-struct RegEnumKeys {
-   struct {
-      /**enumerate subkeys of this key*/
-      POLICY_HND *key;
-
-      /**maximum number of keys to enumerate each call*/
-      uint32 max_keys;
-   } in;
-
-   struct {
-      /**keeps track of the index to resume enumerating*/
-      uint32 resume_idx;
-
-      /**the number of keys returned this call*/
-      uint32 num_keys;
-
-      /**array of key names*/
-      char **key_names;
-
-      /**class names of the keys*/
-      char **class_names;
-
-      /**last modification time of the key*/
-      time_t *mod_times;
-   } out;
-};
-
-/**
- * Enumerates Subkeys of a given key. Can be run in a loop. Example: while(cac_RegEnumKeys(hnd, mem_ctx, op)) { ... }
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized Parameters
- * @see CAC_OP_FAILED()
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_RegEnumKeys(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct RegEnumKeys *op);
-
-
-struct RegCreateKey {
-   struct {
-      /**create a subkey of parent_key*/
-      POLICY_HND *parent_key;
-
-      /**name of the key to create*/
-      char *key_name;
-
-      /**class of the key*/
-      char *class_name;
-
-      /**Access mask to open the key with. See REG_KEY_* in include/rpc_secdes.h*/
-      uint32 access;
-   } in;
-
-   struct {
-      /**Open handle to the key*/
-      POLICY_HND *key;
-   } out;
-};
-
-/**
- * Creates a registry key, if the key already exists, it will be opened __Creating keys is not currently working__.
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized Parmeters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_RegCreateKey(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct RegCreateKey *op);
-
-struct RegDeleteKey {
-   struct {
-      /**handle to open registry key*/
-      POLICY_HND *parent_key;
-
-      /**name of the key to delete*/
-      char *name;
-
-      /**delete recursively. WARNING: this might not always work as planned*/
-      bool recursive;
-   } in;
-
-};
-
-/**
- * Deletes a subkey of an open key. Note: if you run this with op->in.recursive == True, and the operation fails, it may leave the key in an inconsistent state.
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-
-int cac_RegDeleteKey(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct RegDeleteKey *op);
-
-struct RegDeleteValue {
-   struct {
-      /**handle to open registry key*/
-      POLICY_HND *parent_key;
-
-      /**name of the value to delete*/
-      char *name;
-   } in;
-};
-
-/**
- * Deletes a registry value.
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized Parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_RegDeleteValue(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct RegDeleteValue *op);
-
-struct RegQueryKeyInfo {
-   struct {
-      /**Open handle to the key to query*/
-      POLICY_HND *key;
-   } in;
-
-   struct {
-      /**name of the key class*/
-      char *class_name;
-
-      /**number of subkeys of the key*/
-      uint32 num_subkeys;
-
-      /**length (in characters) of the longest subkey name*/
-      uint32 longest_subkey;
-
-      /**length (in characters) of the longest class name*/
-      uint32 longest_class;
-
-      /**number of values in this key*/
-      uint32 num_values;
-
-      /**length (in characters) of the longest value name*/
-      uint32 longest_value_name;
-
-      /**length (in bytes) of the biggest value data*/
-      uint32 longest_value_data;
-
-      /**size (in bytes) of the security descriptor*/
-      uint32 security_desc_size;
-
-      /**time of the last write*/
-      time_t last_write_time;
-   } out;
-};
-
-/**
- * Retrieves information about an open key
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-
-int cac_RegQueryKeyInfo(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct RegQueryKeyInfo *op);
-
-struct RegSaveKey {
-   struct {
-      /**Open key to be saved*/
-      POLICY_HND *key;
-
-      /**The path (on the remote computer) to save the file to*/
-      char *filename;
-   } in;
-};
-
-/**
- * Saves a key to a file on the remote machine __Not currently working__.
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-
-int cac_RegSaveKey(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct RegSaveKey *op);
-
-struct RegQueryValue {
-   struct {
-      /**handle to open registry key*/
-      POLICY_HND *key;
-
-      /**name of the value to query*/
-      char *val_name;
-   } in;
-
-   struct {
-      /**Value type.
-       * One of:
-       *  - REG_DWORD (equivalent to REG_DWORD_LE)
-       *  - REG_DWORD_BE
-       *  - REG_SZ
-       *  - REG_EXPAND_SZ
-       *  - REG_MULTI_SZ
-       *  - REG_BINARY
-       */
-      uint32 type;
-
-      /**The value*/
-      REG_VALUE_DATA *data;
-   } out;
-};
-
-/**
- * Retrieves a value (type and data) _not currently working_.
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-
-int cac_RegQueryValue(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct RegQueryValue *op);
-
-struct RegEnumValues {
-   struct {
-      /**handle to open key*/
-      POLICY_HND *key;
-
-      /**max number of values returned per call*/
-      uint32 max_values;
-
-   } in;
-
-   struct {
-      /**keeps track of the index to resume from - used over multiple calls*/
-      uint32 resume_idx;
-
-      /**the number of values that were returned this call*/
-      uint32 num_values;
-
-      /**Array of value types. A type can be one of:
-       *  - REG_DWORD (equivalent to REG_DWORD_LE)
-       *  - REG_DWORD_BE
-       *  - REG_SZ
-       *  - REG_EXPAND_SZ
-       *  - REG_MULTI_SZ
-       *  - REG_BINARY
-       */
-      uint32 *types;
-
-      /**array of strings storing the names of the values*/
-      char **value_names;
-
-      /**array of pointers to the value data returned*/
-      REG_VALUE_DATA **values;
-   } out;
-};
-
-/**
- * Enumerates a number of Registry values in an open registry key.
- * Can be run in a loop. Example: while(cac_RegEnumValues(hnd, mem_ctx, op)) { ... }
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized Parameters
- * @see CAC_OP_FAILED()
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_RegEnumValues(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct RegEnumValues *op);
-
-struct RegSetValue {
-   struct {
-      /**Handle to open registry key*/
-      POLICY_HND *key;
-
-      /**Name of the value*/
-      char *val_name;
-
-      /**Value type.
-       * One of:
-       *  - REG_DWORD (equivalent to REG_DWORD_LE)
-       *  - REG_DWORD_BE
-       *  - REG_SZ
-       *  - REG_EXPAND_SZ
-       *  - REG_MULTI_SZ
-       *  - REG_BINARY
-       */
-      uint32 type;
-
-      /**the value*/
-      REG_VALUE_DATA value;
-   } in;
-};
-
-/**
- * Sets or creates value (type and data).
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_RegSetValue(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct RegSetValue *op);
-
-struct RegGetVersion {
-   struct {
-      /**open registry key*/
-      POLICY_HND *key;
-   } in;
-
-   struct {
-      /**version number*/
-      uint32 version;
-   } out;
-};
-
-/**
- * Retrieves the registry version number
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_RegGetVersion(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct RegGetVersion *op);
-
-struct RegGetKeySecurity {
-   struct {
-      /**Handle to key to query*/
-      POLICY_HND *key;
-
-      /**Info that you want. Should be a combination of (1 or more or'd):
-       * - OWNER_SECURITY_INFORMATION
-       * - GROUP_SECURITY_INFORMATION
-       * - DACL_SECURITY_INFORMATION
-       * - SACL_SECURITY_INFORMATION
-       * - UNPROTECTED_SACL_SECURITY_INFORMATION
-       * - UNPROTECTED_DACL_SECURITY_INFORMATION
-       * - PROTECTED_SACL_SECURITY_INFORMATION
-       * - PROTECTED_DACL_SECURITY_INFORMATION
-       *
-       * or use:
-       * - ALL_SECURITY_INFORMATION
-       *
-       * all definitions from include/rpc_secdes.h
-       */
-      uint32 info_type;
-   } in;
-
-   struct {
-      /**size of the data returned*/
-      uint32 size;
-
-      /**Security descriptor*/
-      SEC_DESC *descriptor;
-   } out;
-};
-
-/**
- * Retrieves a key security descriptor.
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-
-int cac_RegGetKeySecurity(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct RegGetKeySecurity *op);
-
-struct RegSetKeySecurity {
-   struct {
-      /**Handle to key to query*/
-      POLICY_HND *key;
-
-      /**Info that you want. Should be a combination of (1 or more or'd):
-       * - OWNER_SECURITY_INFORMATION
-       * - GROUP_SECURITY_INFORMATION
-       * - DACL_SECURITY_INFORMATION
-       * - SACL_SECURITY_INFORMATION
-       * - UNPROTECTED_SACL_SECURITY_INFORMATION
-       * - UNPROTECTED_DACL_SECURITY_INFORMATION
-       * - PROTECTED_SACL_SECURITY_INFORMATION
-       * - PROTECTED_DACL_SECURITY_INFORMATION
-       *
-       * or use:
-       * - ALL_SECURITY_INFORMATION
-       *
-       * all definitions from include/rpc_secdes.h
-       */
-      uint32 info_type;
-      
-      /**size of the descriptor*/
-      size_t size;
-
-      /**Security descriptor*/
-      SEC_DESC *descriptor;
-   } in;
-};
-
-/**
- * Sets the key security descriptor.
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_RegSetKeySecurity(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct RegSetKeySecurity *op);
-
-/**@}*/ /*Reg_Functions*/
-
-struct Shutdown {
-   struct {
-      /**the message to display (can be NULL)*/
-      char *message;
-
-      /**timeout in seconds*/
-      uint32 timeout;
-
-      /**False = shutdown, True = reboot*/
-      bool reboot;
-      
-      /**force the*/
-      bool force;
-
-      /*FIXME: make this useful*/
-      uint32 reason;
-   } in;
-};
-
-
-/**
- * Shutdown the server _not currently working_. 
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_Shutdown(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct Shutdown *op);
-
-/**
- * Attempt to abort initiated shutdown on the server _not currently working_. 
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_AbortShutdown(CacServerHandle *hnd, TALLOC_CTX *mem_ctx);
-
-/*****************
- * SAM Functions *
- *****************/
-
-/**@addtogroup SAM_Functions
- * @{
- */
-struct SamConnect {
-   struct {
-      /**Access mask to open with
-       * see generic access masks in include/smb.h*/
-      uint32 access;
-   } in;
-
-   struct {
-      POLICY_HND *sam;
-   } out;
-};
-
-/** 
- * Connects to the SAM. This can be skipped by just calling cac_SamOpenDomain()
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-
-int cac_SamConnect(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamConnect *op);
-
-
-/** 
- * Closes any (SAM, domain, user, group, etc.) SAM handle. 
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param sam Handle to close
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-
-int cac_SamClose(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, POLICY_HND *sam);
-
-struct SamOpenDomain {
-   struct {
-      /**The desired access. See generic access masks - include/smb.h*/
-      uint32 access;
-
-      /**(Optional) An open handle to the SAM. If it is NULL, the function will connect to the SAM with the access mask above*/
-      POLICY_HND *sam;
-
-      /**(Optional) The SID of the domain to open. 
-       *  If this this is NULL, the function will attempt to open the domain specified in hnd->domain */
-      DOM_SID *sid;
-   } in;
-
-   struct {
-      /**handle to the open domain*/
-      POLICY_HND *dom_hnd;
-
-      /**Handle to the open SAM*/
-      POLICY_HND *sam;
-   } out;
-};
-
-/** 
- * Opens a handle to a domain. This must be called before any other SAM functions 
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_SamOpenDomain(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamOpenDomain *op);
-
-struct SamCreateUser {
-   struct {
-      /**Open domain handle*/
-      POLICY_HND *dom_hnd;
-
-      /**Username*/
-      char *name;
-
-      /**See Allowable account control bits in include/smb.h*/
-      uint32 acb_mask;
-   } in;
-
-   struct {
-      /**handle to the user*/
-      POLICY_HND *user_hnd;
-
-      /**rid of the user*/
-      uint32 rid;
-   } out;
-};
-
-/** 
- * Creates a new domain user, if the account already exists it will _not_ be opened and hnd->status will be NT_STATUS_USER_EXISTS
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-
-int cac_SamCreateUser(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamCreateUser *op);
-
-struct SamOpenUser {
-   struct {
-      /**Handle to open SAM connection*/
-      POLICY_HND *dom_hnd;
-
-      /**desired access - see generic access masks in include/smb.h*/
-      uint32 access;
-
-      /**RID of the user*/
-      uint32 rid;
-
-      /**(Optional) name of the user - must supply either RID or user name*/
-      char *name;
-   } in;
-
-   struct {
-      /**Handle to the user*/
-      POLICY_HND *user_hnd;
-   } out;    
-};
-
-/** 
- * Opens a domain user.
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_SamOpenUser(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamOpenUser *op);
-
-/** 
- * Deletes a domain user.  
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param user_hnd Open handle to the user
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_SamDeleteUser(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, POLICY_HND *user_hnd);
-
-
-struct SamEnumUsers {
-   struct {
-      /**Open handle to a domain*/
-      POLICY_HND *dom_hnd;
-
-      /**Enumerate users with specific ACB. If 0, all users will be enumerated*/
-      uint32 acb_mask;
-   } in;
-
-   struct {
-      /**where to resume from. Used over multiple calls*/
-      uint32 resume_idx;
-
-      /**the number of users returned this call*/
-      uint32 num_users;
-
-      /**Array storing the rids of the returned users*/
-      uint32 *rids;
-
-      /**Array storing the names of all the users returned*/
-      char **names;
-
-      bool done;
-   } out;
-};
-
-/** 
- * Enumerates domain users. Can be used as a loop condition. Example: while(cac_SamEnumUsers(hnd, mem_ctx, op)) { ... }
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_SamEnumUsers(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamEnumUsers *op);
-
-struct SamGetNamesFromRids {
-   struct {
-      /**An open handle to the domain SAM from cac_SamOpenDomain()*/
-      POLICY_HND *dom_hnd;
-
-      /**Number of RIDs to resolve*/
-      uint32 num_rids;
-
-      /**Array of RIDs to resolve*/
-      uint32 *rids;
-   } in;
-
-   struct {
-      /**the number of names returned - if this is 0, the map is NULL*/
-      uint32 num_names;
-
-      /**array contiaing the Names and RIDs*/
-      CacLookupRidsRecord *map;
-   } out;
-};
-
-/** 
- * Returns a list of names which map to a list of RIDs.
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_SamGetNamesFromRids(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamGetNamesFromRids *op);
-
-struct SamGetRidsFromNames {
-   struct {
-      /**An open handle to the domain SAM from cac_SamOpenDomain()*/
-      POLICY_HND *dom_hnd;
-
-      /**Number of names to resolve*/
-      uint32 num_names;
-
-      /**Array of names to resolve*/
-      char **names;
-   } in;
-
-   struct {
-      /**the number of names returned - if this is 0, then map is NULL*/
-      uint32 num_rids;
-
-      /**array contiaing the Names and RIDs*/
-      CacLookupRidsRecord *map;
-   } out;
-};
-
-/** 
- * Returns a list of RIDs which map to a list of names.
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_SamGetRidsFromNames(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamGetRidsFromNames *op);
-
-struct SamGetGroupsForUser {
-   struct {
-      /**An open handle to the user*/
-      POLICY_HND *user_hnd;
-   } in;
-
-   struct {
-      /**The number of groups the user is a member of*/
-      uint32 num_groups;
-
-      /**The RIDs of the groups*/
-      uint32 *rids;
-
-      /**The attributes of the groups*/ 
-      uint32 *attributes;
-   } out;
-};
-/** 
- * Retrieves a list of groups that a user is a member of.
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_SamGetGroupsForUser(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamGetGroupsForUser *op);
-
-struct SamOpenGroup {
-   struct {
-      /**Open handle to the domain SAM*/
-      POLICY_HND *dom_hnd;
-
-      /**Desired access to open the group with. See Generic access masks in include/smb.h*/
-      uint32 access;
-
-      /**rid of the group*/
-      uint32 rid;
-   } in;
-
-   struct {
-      /**Handle to the group*/
-      POLICY_HND *group_hnd;
-   } out;
-};
-
-/** 
- * Opens a domain group.
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_SamOpenGroup(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamOpenGroup *op);
-
-struct SamCreateGroup {
-   struct {
-      /**Open handle to the domain SAM*/
-      POLICY_HND *dom_hnd;
-
-      /**Desired access to open the group with. See Generic access masks in include/smb.h*/
-      uint32 access;
-
-      /**The name of the group*/
-      char *name;
-   } in;
-
-   struct {
-      /**Handle to the group*/
-      POLICY_HND *group_hnd;
-   } out;
-};
-
-/** 
- * Creates a group. If the group already exists it will not be opened.
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_SamCreateGroup(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamCreateGroup *op);
-
-/** 
- * Deletes a domain group.  
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param group_hnd Open handle to the group.
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_SamDeleteGroup(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, POLICY_HND *group_hnd);
-
-struct SamGetGroupMembers {
-   struct {
-      /**Open handle to a group*/
-      POLICY_HND *group_hnd;
-   } in;
-
-   struct {
-      /**The number of members in the group*/
-      uint32 num_members;
-
-      /**An array storing the RIDs of the users*/
-      uint32 *rids;
-
-      /**The attributes*/
-      uint32 *attributes;
-   } out;
-};
-
-/** 
- * Retrives a list of users in a group.
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_SamGetGroupMembers(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamGetGroupMembers *op);
-
-struct SamAddGroupMember {
-   struct {
-      /**Open handle to a group*/
-      POLICY_HND *group_hnd;
-
-      /**RID of new member*/
-      uint32 rid;
-   } in;
-};
-
-/** 
- * Adds a user to a group.
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_SamAddGroupMember(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamAddGroupMember *op);
-
-struct SamRemoveGroupMember {
-   struct {
-      /**Open handle to a group*/
-      POLICY_HND *group_hnd;
-
-      /**RID of member to remove*/
-      uint32 rid;
-   } in;
-};
-
-/** 
- * Removes a user from a group.
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_SamRemoveGroupMember(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamRemoveGroupMember *op);
-
-/**
- * Removes all the members of a group - warning: if this function fails is is possible that some but not all members were removed
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param group_hnd Open handle to the group to clear
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_SamClearGroupMembers(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, POLICY_HND *group_hnd);
-
-struct SamSetGroupMembers {
-   struct {
-      /**Open handle to the group*/
-      POLICY_HND *group_hnd;
-
-      /**Number of members in the group - if this is 0, all members of the group will be removed*/
-      uint32 num_members;
-
-      /**The RIDs of the users to add*/
-      uint32 *rids;
-   } in;
-};
-
-/**
- * Clears the members of a group and adds a list of members to the group
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_SamSetGroupMembers(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamSetGroupMembers *op);
-
-struct SamEnumGroups {
-   struct {
-      /**Open handle to a domain*/
-      POLICY_HND *dom_hnd;
-   } in;
-
-   struct {
-      /**Where to resume from _do not_ modify this value. Used over multiple calls.*/
-      uint32 resume_idx;
-
-      /**the number of users returned this call*/
-      uint32 num_groups;
-
-      /**Array storing the rids of the returned groups*/
-      uint32 *rids;
-
-      /**Array storing the names of all the groups returned*/
-      char **names;
-
-      /**Array storing the descriptions of all the groups returned*/
-      char **descriptions;
-
-      bool done;
-   } out;
-};
-
-/** 
- * Enumerates domain groups. Can be used as a loop condition. Example: while(cac_SamEnumGroups(hnd, mem_ctx, op)) { ... }
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_SamEnumGroups(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamEnumGroups *op);
-
-struct SamEnumAliases {
-   struct {
-      /**Open handle to a domain*/
-      POLICY_HND *dom_hnd;
-   } in;
-
-   struct {
-      /**where to resume from. Used over multiple calls*/
-      uint32 resume_idx;
-
-      /**the number of users returned this call*/
-      uint32 num_aliases;
-
-      /**Array storing the rids of the returned groups*/
-      uint32 *rids;
-
-      /**Array storing the names of all the groups returned*/
-      char **names;
-
-      /**Array storing the descriptions of all the groups returned*/
-      char **descriptions;
-
-      bool done;
-   } out;
-};
-
-/** 
- * Enumerates domain aliases. Can be used as a loop condition. Example: while(cac_SamEnumAliases(hnd, mem_ctx, op)) { ... }
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_SamEnumAliases(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamEnumAliases *op);
-
-struct SamCreateAlias {
-   struct {
-      /**Open handle to the domain SAM*/
-      POLICY_HND *dom_hnd;
-
-      /**The name of the alias*/
-      char *name;
-   } in;
-
-   struct {
-      /**Handle to the group*/
-      POLICY_HND *alias_hnd;
-   } out;
-};
-
-/** 
- * Creates an alias. If the alias already exists it will not be opened.
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-
-int cac_SamCreateAlias(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamCreateAlias *op);
-
-struct SamOpenAlias {
-   struct {
-      /**Open handle to the domain SAM*/
-      POLICY_HND *dom_hnd;
-
-      /**Desired access to open the group with. See Generic access masks in include/smb.h*/
-      uint32 access;
-
-      /**rid of the alias*/
-      uint32 rid;
-   } in;
-
-   struct {
-      /**Handle to the alias*/
-      POLICY_HND *alias_hnd;
-   } out;
-};
-
-/** 
- * Opens a handle to an alias.
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_SamOpenAlias(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamOpenAlias *op);
-
-/** 
- * Deletes an alias.
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param alias_hnd Open handle to the alias
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_SamDeleteAlias(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, POLICY_HND *alias_hnd);
-
-struct SamAddAliasMember {
-   struct {
-      /**Open handle to a alias*/
-      POLICY_HND *alias_hnd;
-
-      /**SID of new member*/
-      DOM_SID *sid;
-   } in;
-};
-
-/** 
- * Adds an account to an alias.
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_SamAddAliasMember(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamAddAliasMember *op);
-
-struct SamRemoveAliasMember {
-   struct {
-      /**Open handle to the alias*/
-      POLICY_HND *alias_hnd;
-
-      /**The SID of the member*/
-      DOM_SID *sid;
-   } in;
-};
-
-/** 
- * Removes an account from an alias.
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_SamRemoveAliasMember(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamRemoveAliasMember *op);
-
-struct SamGetAliasMembers {
-   struct {
-      /**Open handle to the alias*/
-      POLICY_HND *alias_hnd;
-   } in;
-
-   struct {
-      /**The number of members*/
-      uint32 num_members;
-
-      /**An array storing the SIDs of the accounts*/
-      DOM_SID *sids;
-   } out;
-};
-
-/** 
- * Retrieves a list of all accounts in an alias.
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_SamGetAliasMembers(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamGetAliasMembers *op);
-
-/**
- * Removes all the members of an alias  - warning: if this function fails is is possible that some but not all members were removed
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param alias_hnd Handle to the alias to clear
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-
-int cac_SamClearAliasMembers(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, POLICY_HND *alias_hnd);
-
-struct SamSetAliasMembers {
-   struct {
-      /**Open handle to the group*/
-      POLICY_HND *alias_hnd;
-
-      /**Number of members in the group - if this is 0, all members of the group will be removed*/
-      uint32 num_members;
-
-      /**The SIDs of the accounts to add*/
-      DOM_SID *sids;
-   } in;
-};
-
-/**
- * Clears the members of an alias and adds a list of members to the alias
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_SamSetAliasMembers(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamSetAliasMembers *op);
-
-
-struct SamUserChangePasswd {
-   struct {
-      /**The username*/
-      char *username;
-
-      /**The current password*/
-      char *password;
-
-      /**The new password*/
-      char *new_password;
-   } in;
-};
-/**Used by a user to change their password*/
-int cac_SamUserChangePasswd(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamUserChangePasswd *op);
-
-/**
- * Enables a user
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param user_hnd Open handle to the user to enable
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_SamEnableUser(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, POLICY_HND *user_hnd);
-
-/**
- * Disables a user
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param user_hnd Open handle to the user to disables
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_SamDisableUser(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, POLICY_HND *user_hnd);
-
-struct SamSetPassword {
-   struct {
-      /**Open handle to a user*/
-      POLICY_HND *user_hnd;
-
-      /**The new password*/
-      char *password;
-   } in;
-};
-
-/**
- * Sets a user's password
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-
-int cac_SamSetPassword(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamSetPassword *op);
-
-struct SamGetUserInfo {
-   struct {
-      /**Open Handle to a user*/
-      POLICY_HND *user_hnd;
-   } in;
-
-   struct {
-      CacUserInfo *info;
-   } out;
-};
-
-/**
- * Retrieves user information using a CacUserInfo structure. If you would like to use a SAM_USERINFO_CTR directly, use cac_SamGetUserInfoCtr()
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @see cac_SamGetUserInfoCtr()
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_SamGetUserInfo(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamGetUserInfo *op);
-
-struct SamSetUserInfo {
-   struct {
-      /**Open handle to a user*/
-      POLICY_HND *user_hnd;
-
-      /**Structure containing the data you would like to set*/
-      CacUserInfo *info;
-   } in;
-};
-
-/**
- * Sets the user info using a CacUserInfo structure. If you would like to use a SAM_USERINFO_CTR directly use cac_SamSetUserInfoCtr().
- * @note All fields in the CacUserInfo structure will be set. Best to call cac_GetUserInfo() modify fields that you want, and then call cac_SetUserInfo().
- * @note When calling this, you _must_ set the user's password.
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @see cac_SamSetUserInfoCtr()
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_SamSetUserInfo(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamSetUserInfo *op);
-
-struct SamGetUserInfoCtr {
-   struct {
-      /**Open handle to a user*/
-      POLICY_HND *user_hnd;
-
-      /**What USER_INFO structure you want. See include/rpc_samr.h*/
-      uint16 info_class;
-   } in;
-
-   struct {
-      /**returned user info*/
-      SAM_USERINFO_CTR *ctr;
-   } out;
-};
-
-/**
- * Retrieves user information using a SAM_USERINFO_CTR structure. If you don't want to use this structure, user SamGetUserInfo()
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @see cac_SamGetUserInfo()
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_SamGetUserInfoCtr(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamGetUserInfoCtr *op);
-
-struct SamSetUserInfoCtr {
-   struct {
-      /**Open handle to a user*/
-      POLICY_HND *user_hnd;
-
-      /**user info - make sure ctr->switch_value is set properly*/
-      SAM_USERINFO_CTR *ctr;
-   } in;
-};
-
-/**
- * Sets the user info using a SAM_USERINFO_CTR structure. If you don't want to use this structure, use cac_SamSetUserInfo()
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @see cac_SamSetUserInfo()
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-
-int cac_SamSetUserInfoCtr(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamSetUserInfoCtr *op);
-
-struct SamRenameUser {
-   struct {
-      /**Open handle to user*/
-      POLICY_HND *user_hnd;
-
-      /**New user name*/
-      char *new_name;
-   } in;
-};
-
-/**
- * Changes the name of a user.
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_SamRenameUser(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamRenameUser *op);
-
-struct SamGetGroupInfo {
-   struct {
-      /**Open handle to a group*/
-      POLICY_HND *group_hnd;
-   } in;
-
-   struct {
-      /**Returned info about the group*/
-      CacGroupInfo *info;
-   } out;
-};
-
-/**
- * Retrieves information about a group.
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_SamGetGroupInfo(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamGetGroupInfo *op);
-
-struct SamSetGroupInfo {
-   struct {
-      /**Open handle to a group*/
-      POLICY_HND *group_hnd;
-
-      /**group info*/
-      CacGroupInfo *info;
-   } in;
-};
-
-/**
- * Sets information about a group.
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_SamSetGroupInfo(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamSetGroupInfo *op);
-
-struct SamRenameGroup {
-   struct {
-      /**Open handle to a group*/
-      POLICY_HND *group_hnd;
-
-      /**New name*/
-      char *new_name;
-   } in;
-};
-
-/**
- * Changes the name of a group
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-
-int cac_SamRenameGroup(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamRenameGroup *op);
-
-struct SamGetAliasInfo {
-   struct {
-      /**Open handle to an alias*/
-      POLICY_HND *alias_hnd;
-   } in;
-
-   struct {
-      /**Returned alias info*/
-      CacAliasInfo *info;
-   } out;
-};
-
-/**
- * Retrieves information about an alias.
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_SamGetAliasInfo(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamGetAliasInfo *op);
-
-struct SamSetAliasInfo {
-   struct {
-      /**Open handle to an alias*/
-      POLICY_HND *alias_hnd;
-      
-      /**Returned alias info*/
-      CacAliasInfo *info;
-   } in;
-};
-
-/**
- * Sets information about an alias.
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE The operation could not complete successfully. hnd->status is set with appropriate NTSTATUS code
- * @return CAC_SUCCESS The operation completed successfully
- */
-int cac_SamSetAliasInfo(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamSetAliasInfo *op);
-
-struct SamGetDomainInfo {
-   struct {
-      /**Open handle to the domain SAM*/
-      POLICY_HND *dom_hnd;
-   } in;
-
-   struct {
-      /**Returned domain info*/
-      CacDomainInfo *info;
-   } out;
-};
-
-/**
- * Gets domain information in the form of a CacDomainInfo structure. 
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @see SamGetDomainInfoCtr()
- * @return CAC_FAILURE - the operation was not successful hnd->status is set appropriately
- * @return CAC_SUCCESS - the operation was successful
- * @return CAC_PARTIAL_SUCCESS - This function makes 3 rpc calls, if one or two fail and the rest succeed, 
- *                                  not all fields in the CacDomainInfo structure will be filled
- */
-int cac_SamGetDomainInfo(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamGetDomainInfo *op);
-
-struct SamGetDomainInfoCtr {
-   struct {
-      /**Open handle to domain*/
-      POLICY_HND *dom_hnd;
-
-      /**What info level you want*/
-      uint16 info_class;
-   } in;
-
-   struct {
-      SAM_UNK_CTR *info;
-   } out;
-};
-
-/**
- * Gets domain information in the form of a SAM_UNK_CTR structure. 
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @see SamGetDomainInfo()
- * @return CAC_FAILURE - the operation was not successful hnd->status is set appropriately
- * @return CAC_SUCCESS - the operation was successful
- */
-int cac_SamGetDomainInfoCtr(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamGetDomainInfoCtr *op);
-
-struct SamGetDisplayInfo {
-   struct {
-      /**Open handle to domain*/
-      POLICY_HND *dom_hnd;
-
-      /**What type of data*/
-      uint16 info_class;
-
-      /**(Optional)If 0, max_entries and max_size will be filled in by the function*/
-      uint32 max_entries;
-      
-      /**(Optional)If 0, max_entries and max_size will be filled in by the function*/
-      uint32 max_size;
-   } in;
-
-   struct {
-      /**Do not modify this value, use the same value between multiple calls (ie in while loop)*/
-      uint32 resume_idx;
-
-      /**Number of entries returned*/
-      uint32 num_entries;
-
-      /**Returned display info*/
-      SAM_DISPINFO_CTR ctr;
-
-      /**Internal value. Do not modify.*/
-      uint32 loop_count;
-
-      bool done;
-   } out;
-};
-
-/**
- * Gets dislpay information using a SAM_DISPINFO_CTR.
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE - the operation was not successful hnd->status is set appropriately
- * @return CAC_SUCCESS - the operation was successful
- */
-int cac_SamGetDisplayInfo(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamGetDisplayInfo *op);
-
-struct SamLookupDomain {
-   struct {
-      /**Open handle to the sam (opened with cac_SamConnect() or cac_SamOpenDomain()*/
-      POLICY_HND *sam;
-
-      /**Name of the domain to lookup*/
-      char *name;
-   } in;
-
-   struct {
-      /**SID of the domain*/
-      DOM_SID *sid;
-   } out;
-};
-
-/**
- * Looks up a Domain SID given it's name.
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE - the operation was not successful hnd->status is set appropriately
- * @return CAC_SUCCESS - the operation was successful
- */
-int cac_SamLookupDomain(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamLookupDomain *op);
-
-struct SamGetSecurityObject {
-   struct {
-      /**An open handle (SAM, domain or user)*/
-      POLICY_HND *pol;
-   } in;
-
-   struct {
-      SEC_DESC_BUF *sec;
-   } out;
-};
-
-/**
- * Retrievies Security descriptor information for a SAM/Domain/user
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE - the operation was not successful hnd->status is set appropriately
- * @return CAC_SUCCESS - the operation was successful
- */
-int cac_SamGetSecurityObject(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamGetSecurityObject *op);
-
-struct SamFlush {
-   struct {
-      /**Open handle to the domain SAM*/
-      POLICY_HND *dom_hnd;
-
-      /**(Optional)Domain SID. If NULL, the domain in hnd->domain will be opened*/
-      DOM_SID *sid;
-
-      /**(Optional)Desired access to re-open the domain with. If 0, MAXIMUM_ALLOWED_ACCESS is used.*/
-      uint32 access;
-   } in;
-};
-
-/**
- * Closes the domain handle, then re-opens it - effectively flushing any changes made.
- * WARNING: if this fails you will no longer have an open handle to the domain SAM.
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized Parameters
- * @return CAC_FAILURE - the operation was not successful hnd->status is set appropriately
- * @return CAC_SUCCESS - the operation was successful
- */
-int cac_SamFlush(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SamFlush *op);
-
-/**@}*/ /*SAM_Functions*/
-
-/**@addtogroup SCM_Functions
- * @{
- */
-
-struct SvcOpenScm {
-   struct {
-      /**Desired access to open the Handle with. See SC_RIGHT_MGR_* or SC_MANAGER_* in include/rpc_secdes.h*/
-      uint32 access;
-   } in;
-
-   struct {
-      /**Handle to the SCM*/
-      POLICY_HND *scm_hnd;
-   } out;
-};
-
-/**
- * Opens a handle to the SCM on the remote machine.
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE - the operation was not successful hnd->status is set appropriately
- * @return CAC_SUCCESS - the operation was successful
- */
-int cac_SvcOpenScm(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SvcOpenScm *op);
-
-/**
- * Closes an Svc handle (SCM or Service)
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param scm_hnd The handle to close
- * @return CAC_FAILURE - the operation was not successful hnd->status is set appropriately
- * @return CAC_SUCCESS - the operation was successful
- */
-int cac_SvcClose(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, POLICY_HND *scm_hnd);
-
-struct SvcEnumServices {
-   struct {
-      /**Open handle to the SCM*/
-      POLICY_HND *scm_hnd;
-
-      /**(Optional)Type of service to enumerate. Possible values:
-       *  - SVCCTL_TYPE_WIN32
-       *  - SVCCTL_TYPE_DRIVER
-       *  If this is 0, (SVCCTL_TYPE_DRIVER | SVCCTL_TYPE_WIN32) is assumed.
-       */
-      uint32 type;
-
-      /**(Optional)State of service to enumerate. Possible values:
-       *  - SVCCTL_STATE_ACTIVE
-       *  - SVCCTL_STATE_INACTIVE
-       *  - SVCCTL_STATE_ALL
-       *  If this is 0, SVCCTL_STATE_ALL is assumed.
-       */
-      uint32 state;
-   } in;
-   
-   struct {
-      /**Number of services returned*/
-      uint32 num_services;
-
-      /**Array of service structures*/
-      CacService *services;
-   } out;
-};
-
-/**
- * Enumerates services on the remote machine.
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized parameters
- * @return CAC_FAILURE - the operation was not successful hnd->status is set appropriately
- * @return CAC_SUCCESS - the operation was successful
- */
-int cac_SvcEnumServices(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SvcEnumServices *op);
-
-struct SvcOpenService {
-   struct {
-      /**Handle to the Service Control Manager*/
-      POLICY_HND *scm_hnd;
-
-      /**Access mask to open service with see SERVICE_* or SC_RIGHT_SVC_* in include/rpc_secdes.h*/
-      uint32 access;
-
-      /**The name of the service. _not_ the display name*/
-      char *name;
-   } in;
-
-   struct {
-      /**Handle to the open service*/
-      POLICY_HND *svc_hnd;
-   } out;
-};
-
-/**
- * Opens a handle to a service.
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized Parameters
- * @return CAC_FAILURE - the operation was not successful hnd->status is set appropriately
- * @return CAC_SUCCESS - the operation was successful
- */
-
-int cac_SvcOpenService(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SvcOpenService *op);
-
-struct SvcGetStatus {
-   struct {
-      /**Open handle to the service to query*/
-      POLICY_HND *svc_hnd;
-   } in;
-
-   struct {
-      /**The status of the service. See include/rpc_svcctl.h for SERVICE_STATUS definition.*/
-      SERVICE_STATUS status;
-   } out;
-};
-
-/**
- * Retrieves the status of a service.
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized Parameters
- * @return CAC_FAILURE - the operation was not successful hnd->status is set appropriately
- * @return CAC_SUCCESS - the operation was successful
- */
-int cac_SvcGetStatus(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SvcGetStatus *op);
-
-struct SvcStartService {
-   struct {
-      /**open handle to the service*/
-      POLICY_HND *svc_hnd;
-
-      /**Array of parameters to start the service with. Can be NULL if num_parms is 0*/
-      char **parms;
-
-      /**Number of parameters in the parms array*/
-      uint32 num_parms;
-
-      /**Number of seconds to wait for the service to actually start. If this is 0, then the status will not be checked after the initial call*/
-      uint32 timeout;
-   } in;
-};
-
-/**
- * Attempts to start a service.
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized Parameters
- * @return CAC_FAILURE - the operation was not successful hnd->status is set appropriately
- * @return CAC_SUCCESS - the operation was successful
- */
-
-int cac_SvcStartService(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SvcStartService *op);
-
-struct SvcControlService {
-   struct {
-      /**Open handle to the service to control*/
-      POLICY_HND *svc_hnd;
-
-      /**The control operation to perform. Possible values (from include/rpc_svcctl.h):
-       * - SVCCTL_CONTROL_STOP
-       * - SVCCTL_CONTROL_PAUSE
-       * - SVCCTL_CONTROL_CONTINUE
-       * - SVCCTL_CONTROL_SHUTDOWN
-       */
-      uint32 control;
-   } in;
-
-   struct {
-      /**The returned status of the service, _immediately_ after the call*/
-      SERVICE_STATUS *status;
-   } out;
-};
-
-/**
- * Performs a control operation on a service and _immediately_ returns.
- * @see cac_SvcStopService()
- * @see cac_SvcPauseService()
- * @see cac_SvcContinueService()
- * @see cac_SvcShutdownService()
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized Parameters
- * @return CAC_FAILURE - the operation was not successful hnd->status is set appropriately
- * @return CAC_SUCCESS - the operation was successful
- */
-int cac_SvcControlService(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SvcControlService *op);
-
-struct SvcStopService {
-   struct {
-      /**Open handle to the service*/
-      POLICY_HND *svc_hnd;
-
-      /**Number of seconds to wait for the service to actually start. 
-       * If this is 0, then the status will not be checked after the initial call and CAC_SUCCESS might be returned if the status isn't actually started
-       */
-      uint32 timeout;
-   } in;
-
-   struct {
-      /**Status of the service after the operation*/
-      SERVICE_STATUS status;
-   } out;
-};
-
-/**
- * Attempts to stop a service.
- * @see cacSvcControlService()
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized Parameters
- * @return CAC_FAILURE - the operation was not successful. If hnd->status is NT_STATUS_OK, then a timeout occured.
- * @return CAC_SUCCESS - the operation was successful
- */
-int cac_SvcStopService(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SvcStopService *op);
-
-struct SvcPauseService {
-   struct {
-      /**Open handle to the service*/
-      POLICY_HND *svc_hnd;
-
-      /**Number of seconds to wait for the service to actually start. 
-       * If this is 0, then the status will not be checked after the initial call and CAC_SUCCESS might be returned if the status isn't actually started
-       */
-      uint32 timeout;
-   } in;
-
-   struct {
-      /**Status of the service after the operation*/
-      SERVICE_STATUS status;
-   } out;
-};
-
-/**
- * Attempts to pause a service.
- * @see cacSvcControlService()
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized Parameters
- * @return CAC_FAILURE - the operation was not successful. If hnd->status is NT_STATUS_OK, then a timeout occured.
- * @return CAC_SUCCESS - the operation was successful
- */
-int cac_SvcPauseService(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SvcPauseService *op);
-
-struct SvcContinueService {
-   struct {
-      /**Open handle to the service*/
-      POLICY_HND *svc_hnd;
-
-      /**Number of seconds to wait for the service to actually start. 
-       * If this is 0, then the status will not be checked after the initial call and CAC_SUCCESS might be returned if the status isn't actually started
-       */
-      uint32 timeout;
-   } in;
-
-   struct {
-      /**Status of the service after the operation*/
-      SERVICE_STATUS status;
-   } out;
-};
-
-/**
- * Attempts to continue a paused service.
- * @see cacSvcControlService()
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized Parameters
- * @return CAC_FAILURE - the operation was not successful. If hnd->status is NT_STATUS_OK, then a timeout occured.
- * @return CAC_SUCCESS - the operation was successful
- */
-int cac_SvcContinueService(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SvcContinueService *op);
-
-struct SvcGetDisplayName {
-   struct {
-      /**Open handle to the service*/
-      POLICY_HND *svc_hnd;
-   } in;
-
-   struct {
-      /**The returned display name of the service*/
-      char *display_name;
-   } out;
-};
-
-/**
- * Retrieves the display name of a service _not currently working_
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized Parameters
- * @return CAC_FAILURE - the operation was not successful hnd->status is set appropriately
- * @return CAC_SUCCESS - the operation was successful
- */
-int cac_SvcGetDisplayName(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SvcGetDisplayName *op);
-
-struct SvcGetServiceConfig {
-   struct {
-      /**Open handle to the service*/
-      POLICY_HND *svc_hnd;
-   } in;
-
-   struct {
-      /**Returned Configuration information*/
-      CacServiceConfig config;
-   } out;
-};
-
-/**
- * Retrieves configuration information about a service.
- * @param hnd Initialized and connected server handle
- * @param mem_ctx Context for memory allocation
- * @param op Initialized Parameters
- * @return CAC_FAILURE - the operation was not successful hnd->status is set appropriately
- * @return CAC_SUCCESS - the operation was successful
- */
-int cac_SvcGetServiceConfig(CacServerHandle *hnd, TALLOC_CTX *mem_ctx, struct SvcGetServiceConfig *op);
-
-/**@}*/ /*SCM_Functions*/
-
-struct rpc_pipe_client *cac_GetPipe(CacServerHandle *hnd, int pi_idx);
-
-#endif /* LIBMSRPC_H */
-
-
diff --git a/source3/include/libmsrpc_internal.h b/source3/include/libmsrpc_internal.h
deleted file mode 100644 (file)
index 623c43f..0000000
+++ /dev/null
@@ -1,73 +0,0 @@
-/* 
- *  Unix SMB/CIFS implementation.
- *  MS-RPC client internal definitions
- *  Copyright (C) Chris Nicholls              2005.
- *  
- *  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/>.
- */
-
-#ifndef LIBMSRPC_INTERNAL_H
-#define LIBMSRPC_INTERNAL_H
-
-#include "libmsrpc.h"
-
-/*definitions*/
-
-struct CacServerHandleInternal {
-   /*stores the os type of the server*/
-   uint16 srv_level;
-
-   /*stores the initialized/active pipes*/
-   bool pipes[PI_MAX_PIPES];
-
-   /*underlying smbc context*/
-   SMBCCTX *ctx;
-
-   /*did the user supply this SMBCCTX?*/
-   bool user_supplied_ctx;
-};
-
-/*used to get a struct rpc_pipe_client* to be passed into rpccli* calls*/
-
-/*nessecary prototypes*/
-bool rid_in_list(uint32 rid, uint32 *list, uint32 list_len);
-
-int cac_ParseRegPath(char *path, uint32 *reg_type, char **key_name);
-
-REG_VALUE_DATA *cac_MakeRegValueData(TALLOC_CTX *mem_ctx, uint32 data_type, REGVAL_BUFFER buf);
-
-RPC_DATA_BLOB *cac_MakeRpcDataBlob(TALLOC_CTX *mem_ctx, uint32 data_type, REG_VALUE_DATA data);
-
-SAM_USERINFO_CTR *cac_MakeUserInfoCtr(TALLOC_CTX *mem_ctx, CacUserInfo *info);
-
-CacUserInfo *cac_MakeUserInfo(TALLOC_CTX *mem_ctx, SAM_USERINFO_CTR *ctr);
-CacGroupInfo *cac_MakeGroupInfo(TALLOC_CTX *mem_ctx, GROUP_INFO_CTR *ctr);
-GROUP_INFO_CTR *cac_MakeGroupInfoCtr(TALLOC_CTX *mem_ctx, CacGroupInfo *info);
-CacAliasInfo *cac_MakeAliasInfo(TALLOC_CTX *mem_ctx, ALIAS_INFO_CTR ctr);
-ALIAS_INFO_CTR *cac_MakeAliasInfoCtr(TALLOC_CTX *mem_ctx, CacAliasInfo *info);
-CacDomainInfo *cac_MakeDomainInfo(TALLOC_CTX *mem_ctx, SAM_UNK_INFO_1 *info1, SAM_UNK_INFO_2 *info2, SAM_UNK_INFO_12 *info12);
-CacService *cac_MakeServiceArray(TALLOC_CTX *mem_ctx, ENUM_SERVICES_STATUS *svc, uint32 num_services);
-int cac_InitCacServiceConfig(TALLOC_CTX *mem_ctx, SERVICE_CONFIG *src, CacServiceConfig *dest);
-
-/*moved to libmsrpc.h*/
-/*struct rpc_pipe_client *cac_GetPipe(CacServerHandle *hnd, int pi_idx);*/
-
-SMBCSRV *smbc_attr_server(SMBCCTX *context,
-                          const char *server, const char *share, 
-                          fstring workgroup,
-                          fstring username, fstring password,
-                          POLICY_HND *pol);
-
-
-#endif /* LIBMSRPC_INTERNAL_H */
index 4377e3330a1cfcf5514c498cf4581ccc679cc964..a7d46e72d8c9516bd723a5272d0f37c95a41b53a 100644 (file)
@@ -539,17 +539,6 @@ struct packet_struct
        } packet;
 };
 
-/* NETLOGON opcodes */
-
-#define QUERYFORPDC     7 /* Query for PDC. */
-#define SAM_UAS_CHANGE  10 /* Announce change to UAS or SAM. */
-#define QUERYFORPDC_R  12 /* Response to Query for PDC. */
-#define SAMLOGON       18
-#define SAMLOGON_R     19
-#define SAMLOGON_UNK_R 21
-#define SAMLOGON_AD_UNK_R 23
-#define SAMLOGON_AD_R   25
-
 /* Ids for netbios packet types. */
 
 #define ANN_HostAnnouncement         1
index 04e30a011b73387dc45efd91b605444329fff434..d91917b528a071e06854a62fd7fc2415a802587c 100644 (file)
@@ -77,7 +77,7 @@ extern struct printif iprint_printif;
 #define NEXT_JOBID(j) ((j+1) % PRINT_MAX_JOBID > 0 ? (j+1) % PRINT_MAX_JOBID : 1)
 
 #define MAX_CACHE_VALID_TIME 3600
-#define CUPS_DEFAULT_TIMEOUT 30
+#define CUPS_DEFAULT_CONNECTION_TIMEOUT 30
 
 #ifndef PRINT_SPOOL_PREFIX
 #define PRINT_SPOOL_PREFIX "smbprn."
index 198248c5172704e1be0aca673f03b1906c6134eb..3df87a6c346d7682d885931f1de5630bd331739b 100644 (file)
@@ -43,7 +43,10 @@ bool password_ok(const char *smb_name, DATA_BLOB password_blob);
 
 /* The following definitions come from auth/auth_domain.c  */
 
-NTSTATUS auth_domain_init(void) ;
+void attempt_machine_password_change(void);
+NTSTATUS auth_domain_init(void);
+
+NTSTATUS auth_netlogond_init(void);
 
 /* The following definitions come from auth/auth_ntlmssp.c  */
 
@@ -489,7 +492,7 @@ TALLOC_CTX *debug_ctx(void);
 /* The following definitions come from lib/display_sec.c  */
 
 char *get_sec_mask_str(TALLOC_CTX *ctx, uint32 type);
-void display_sec_access(SEC_ACCESS *info);
+void display_sec_access(uint32_t *info);
 void display_sec_ace_flags(uint8_t flags);
 void display_sec_ace(SEC_ACE *ace);
 void display_sec_acl(SEC_ACL *sec_acl);
@@ -507,6 +510,7 @@ void display_set_stderr(void);
 /* The following definitions come from lib/errmap_unix.c  */
 
 NTSTATUS map_nt_error_from_unix(int unix_error);
+int map_errno_from_nt_status(NTSTATUS status);
 
 /* The following definitions come from lib/events.c  */
 
@@ -702,6 +706,7 @@ bool privilege_set_to_se_priv( SE_PRIV *mask, struct lsa_PrivilegeSet *privset )
 
 /* The following definitions come from lib/readline.c  */
 
+void smb_readline_done(void);
 char *smb_readline(const char *prompt, void (*callback)(void),
                   char **(completion_fn)(const char *text, int start, int end));
 const char *smb_readline_get_line_buffer(void);
@@ -766,7 +771,6 @@ NTSTATUS sec_desc_mod_sid(SEC_DESC *sd, DOM_SID *sid, uint32 mask);
 NTSTATUS sec_desc_del_sid(TALLOC_CTX *ctx, SEC_DESC **psd, DOM_SID *sid, size_t *sd_size);
 SEC_DESC_BUF *se_create_child_secdesc(TALLOC_CTX *ctx, SEC_DESC *parent_ctr, 
                                      bool child_container);
-void init_sec_access(uint32 *t, uint32 mask);
 
 /* The following definitions come from lib/select.c  */
 
@@ -1421,6 +1425,7 @@ WERROR registry_push_value(TALLOC_CTX *mem_ctx,
 /* The following definitions come from lib/util_seaccess.c  */
 
 void se_map_generic(uint32 *access_mask, const struct generic_mapping *mapping);
+void security_acl_map_generic(struct security_acl *sa, const struct generic_mapping *mapping);
 void se_map_standard(uint32 *access_mask, struct standard_mapping *mapping);
 bool se_access_check(const SEC_DESC *sd, const NT_USER_TOKEN *token,
                     uint32 acc_desired, uint32 *acc_granted, 
@@ -5819,7 +5824,7 @@ const char **lp_svcctl_list(void);
 char *lp_cups_options(int );
 char *lp_cups_server(void);
 char *lp_iprint_server(void);
-int lp_cups_timeout(void);
+int lp_cups_connection_timeout(void);
 const char *lp_ctdbd_socket(void);
 const char **lp_cluster_addresses(void);
 bool lp_clustering(void);
@@ -5985,7 +5990,7 @@ bool dump_a_parameter(int snum, char *parm_name, FILE * f, bool isGlobal);
 struct parm_struct *lp_get_parameter(const char *param_name);
 struct parm_struct *lp_next_parameter(int snum, int *i, int allparameters);
 bool lp_snum_ok(int iService);
-void lp_add_one_printer(char *name, char *comment);
+void lp_add_one_printer(const char *name, const char *comment, void *pdata);
 bool lp_loaded(void);
 void lp_killunused(bool (*snumused) (int));
 void lp_kill_all_services(void);
@@ -6414,6 +6419,8 @@ bool secrets_restore_schannel_session_info(TALLOC_CTX *mem_ctx,
                                struct dcinfo **ppdc);
 bool secrets_store_generic(const char *owner, const char *key, const char *secret);
 char *secrets_fetch_generic(const char *owner, const char *key);
+bool secrets_store_local_schannel_key(uint8_t schannel_key[16]);
+bool secrets_fetch_local_schannel_key(uint8_t schannel_key[16]);
 
 /* The following definitions come from passdb/util_builtin.c  */
 
@@ -6556,11 +6563,15 @@ char* get_server_name( Printer_entry *printer );
 
 /* The following definitions come from printing/pcap.c  */
 
+bool pcap_cache_add_specific(struct pcap_cache **ppcache, const char *name, const char *comment);
+void pcap_cache_destroy_specific(struct pcap_cache **ppcache);
 bool pcap_cache_add(const char *name, const char *comment);
 bool pcap_cache_loaded(void);
+void pcap_cache_replace(const struct pcap_cache *cache);
 void pcap_cache_reload(void);
 bool pcap_printername_ok(const char *printername);
-void pcap_printer_fn(void (*fn)(char *, char *));
+void pcap_printer_fn_specific(const struct pcap_cache *, void (*fn)(const char *, const char *, void *), void *);
+void pcap_printer_fn(void (*fn)(const char *, const char *, void *), void *);
 
 /* The following definitions come from printing/print_aix.c  */
 
@@ -9545,7 +9556,6 @@ NTSTATUS open_fake_file(connection_struct *conn,
                                const char *fname,
                                uint32 access_mask,
                                files_struct **result);
-void destroy_fake_file_handle(struct fake_file_handle **fh);
 NTSTATUS close_fake_file(files_struct *fsp);
 
 /* The following definitions come from smbd/file_access.c  */
@@ -9911,14 +9921,17 @@ void reply_pipe_close(connection_struct *conn, struct smb_request *req);
 
 /* The following definitions come from smbd/posix_acls.c  */
 
-NTSTATUS unpack_nt_owners(int snum, uid_t *puser, gid_t *pgrp, uint32 security_info_sent, SEC_DESC *psd);
+NTSTATUS unpack_nt_owners(int snum, uid_t *puser, gid_t *pgrp, uint32 security_info_sent, const SEC_DESC *psd);
 SMB_ACL_T free_empty_sys_acl(connection_struct *conn, SMB_ACL_T the_acl);
 NTSTATUS posix_fget_nt_acl(struct files_struct *fsp, uint32_t security_info,
                           SEC_DESC **ppdesc);
 NTSTATUS posix_get_nt_acl(struct connection_struct *conn, const char *name,
                          uint32_t security_info, SEC_DESC **ppdesc);
 int try_chown(connection_struct *conn, const char *fname, uid_t uid, gid_t gid);
-NTSTATUS set_nt_acl(files_struct *fsp, uint32 security_info_sent, SEC_DESC *psd);
+NTSTATUS append_parent_acl(files_struct *fsp,
+                               const SEC_DESC *pcsd,
+                               SEC_DESC **pp_new_sd);
+NTSTATUS set_nt_acl(files_struct *fsp, uint32 security_info_sent, const SEC_DESC *psd);
 int get_acl_group_bits( connection_struct *conn, const char *fname, mode_t *mode );
 int chmod_acl(connection_struct *conn, const char *name, mode_t mode);
 int inherit_access_posix_acl(connection_struct *conn, const char *inherit_from_dir,
index 83103b73869c1780aee22c56896ef6de39859c38..71fba41fe949da76bd7b67011af9975b084e8a5c 100644 (file)
@@ -70,9 +70,6 @@
                                        PROTECTED_SACL_SECURITY_INFORMATION|\
                                        PROTECTED_DACL_SECURITY_INFORMATION)
 
-/* SEC_ACCESS */
-typedef uint32 SEC_ACCESS;
-
 /* SEC_ACE */
 typedef struct security_ace SEC_ACE;
 #define  SEC_ACE_HEADER_SIZE (2 * sizeof(uint8) + sizeof(uint16) + sizeof(uint32))
index d9f457558bf6db2c9f5a89d34968eaaadd5f55e0..3c8e2ccf81ac166f5d9926c2f2f3580787e13726 100644 (file)
@@ -45,6 +45,8 @@
 
 #define SECRETS_LDAP_BIND_PW "SECRETS/LDAP_BIND_PW"
 
+#define SECRETS_LOCAL_SCHANNEL_KEY "SECRETS/LOCAL_SCHANNEL_KEY"
+
 /* Authenticated user info is stored in secrets.tdb under these keys */
 
 #define SECRETS_AUTH_USER      "SECRETS/AUTH_USER"
index c8c4f8c3cc98453750b1189e914e0cf7ec433a10..ef98b5e1b545bc3b52635d2b90f82694d95352e5 100644 (file)
@@ -391,6 +391,7 @@ struct idle_event;
 struct share_mode_entry;
 struct uuid;
 struct named_mutex;
+struct pcap_cache;
 
 struct vfs_fsp_data {
     struct vfs_fsp_data *next;
index 20e2a9a4437f2d375b00dcabd6405f3c5227434e..d2e0aa95acefa239b2c4fe135614815d1c998c56 100644 (file)
                                return ERROR_NT(NT_STATUS_INVALID_HANDLE); \
                        } while(0)
 
-/* you must add the following extern declaration to files using this macro
- * (do not add it to the macro as that causes nested extern declaration warnings)
- * extern struct current_user current_user;
- */
-#define CHECK_FSP(fsp,conn) do {\
-                       if (!(fsp) || !(conn)) \
-                               return ERROR_NT(NT_STATUS_INVALID_HANDLE); \
-                       else if (((conn) != (fsp)->conn) || current_user.vuid != (fsp)->vuid) \
-                               return ERROR_NT(NT_STATUS_INVALID_HANDLE); \
-                       else if ((fsp)->is_directory) \
-                               return ERROR_NT(NT_STATUS_INVALID_DEVICE_REQUEST); \
-                       else if ((fsp)->fh->fd == -1) \
-                               return ERROR_NT(NT_STATUS_ACCESS_DENIED); \
-                       (fsp)->num_smb_operations++;\
-                       } while(0)
-
 #define CHECK_READ(fsp,inbuf) (((fsp)->fh->fd != -1) && ((fsp)->can_read || \
                        ((SVAL((inbuf),smb_flg2) & FLAGS2_READ_PERMIT_EXECUTE) && \
                         (fsp->access_mask & FILE_EXECUTE))))
index 9b72f6932893b234f84fb4ce53f784716bfb0678..a3d38f6a25d2becaa3686d814b7400a73fe4c42f 100644 (file)
 /* Leave at 22 - not yet released. Remove parameter fd from close_fn. - obnox */
 /* Changed to version 23 - remove set_nt_acl call. This can only be done via an
    open handle. JRA. */
+/* Changed to version 24 - make security descriptor const in fset_nt_acl. JRA. */
 
-#define SMB_VFS_INTERFACE_VERSION 23
+#define SMB_VFS_INTERFACE_VERSION 24
 
 
 /* to bug old modules which are trying to compile with the old functions */
@@ -365,7 +366,7 @@ struct vfs_ops {
                NTSTATUS (*fset_nt_acl)(struct vfs_handle_struct *handle,
                                        struct files_struct *fsp,
                                        uint32 security_info_sent,
-                                       struct security_descriptor *psd);
+                                       const struct security_descriptor *psd);
 
                /* POSIX ACL operations. */
 
index 1a4c27ba205e53ac8534956c5495ce9cc48dbd16..ffba6de83245a147d2b13772aaae38ad3b0d5f8b 100644 (file)
@@ -658,12 +658,13 @@ struct async_req *async_connect(TALLOC_CTX *mem_ctx, struct event_context *ev,
 
        state->fde = event_add_fd(ev, state, fd,
                                  EVENT_FD_READ | EVENT_FD_WRITE,
-                                 async_connect_callback, state);
+                                 async_connect_callback, result);
        if (state->fde == NULL) {
                sys_fcntl_long(fd, F_SETFL, p->old_sockflags);
                TALLOC_FREE(result);
                return NULL;
        }
+       result->private_data = state;
 
        state->param.param_connect.fd = fd;
        state->param.param_connect.address = address;
index 1ae23bcf8270f482d65ccdb5698b3cfc8a70a5dc..5075476e948eddd60a568e72fe5e23ad22ca5818 100644 (file)
@@ -260,7 +260,7 @@ static struct messaging_rec *ctdb_pull_messaging_rec(TALLOC_CTX *mem_ctx,
        blob = data_blob_const(msg->data, msg->datalen);
 
        ndr_err = ndr_pull_struct_blob(
-               &blob, result, result,
+               &blob, result, NULL, result,
                (ndr_pull_flags_fn_t)ndr_pull_messaging_rec);
 
        if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
@@ -636,7 +636,7 @@ NTSTATUS ctdbd_messaging_send(struct ctdbd_connection *conn,
        }
 
        ndr_err = ndr_push_struct_blob(
-               &blob, mem_ctx, msg,
+               &blob, mem_ctx, NULL, msg,
                (ndr_push_flags_fn_t)ndr_push_messaging_rec);
 
        if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
index 63a5ce4de6782f858342447757cec563605d5a85..2818634b14386224a1fe7d2dfeac6f7426661581 100644 (file)
@@ -405,8 +405,9 @@ static struct db_record *db_ctdb_fetch_locked_transaction(struct db_ctdb_ctx *ct
        return result;
 }
 
-static int db_ctdb_record_destructor(struct db_record *rec)
+static int db_ctdb_record_destructor(struct db_record **recp)
 {
+       struct db_record *rec = talloc_get_type_abort(*recp, struct db_record);
        struct db_ctdb_transaction_handle *h = talloc_get_type_abort(
                rec->private_data, struct db_ctdb_transaction_handle);
        int ret = h->ctx->db->transaction_commit(h->ctx->db);
@@ -424,7 +425,7 @@ static struct db_record *db_ctdb_fetch_locked_persistent(struct db_ctdb_ctx *ctx
                                                         TDB_DATA key)
 {
        int res;
-       struct db_record *rec;
+       struct db_record *rec, **recp;
 
        res = db_ctdb_transaction_start(ctx->db);
        if (res == -1) {
@@ -438,7 +439,14 @@ static struct db_record *db_ctdb_fetch_locked_persistent(struct db_ctdb_ctx *ctx
        }
 
        /* destroy this transaction when we release the lock */
-       talloc_set_destructor((struct db_record *)talloc_new(rec), db_ctdb_record_destructor);
+       recp = talloc(rec, struct db_record *);
+       if (recp == NULL) {
+               ctx->db->transaction_cancel(ctx->db);
+               talloc_free(rec);
+               return NULL;
+       }
+       *recp = rec;
+       talloc_set_destructor(recp, db_ctdb_record_destructor);
        return rec;
 }
 
index d835ea7c176e5a824b387a587f21ba94991bf6e5..d91b55dd23b70c150b4ee26c0b98dae7eddee830 100644 (file)
@@ -578,7 +578,9 @@ void setup_logging(const char *pname, bool interactive)
        stdout_logging = False;
        if (dbf) {
                x_fflush(dbf);
-               (void) x_fclose(dbf);
+                if (dbf != x_stdout) {
+                        (void) x_fclose(dbf);
+                }
        }
 
        dbf = NULL;
index 67392e45688c5478ddc7c06d3570a7e96535ebea..5427a8173ee09bcf3f727e413ca15608e2c7bfc0 100644 (file)
@@ -118,7 +118,7 @@ char *get_sec_mask_str(TALLOC_CTX *ctx, uint32 type)
 /****************************************************************************
  display sec_access structure
  ****************************************************************************/
-void display_sec_access(SEC_ACCESS *info)
+void display_sec_access(uint32_t *info)
 {
        char *mask_str = get_sec_mask_str(NULL, *info);
        printf("\t\tPermissions: 0x%x: %s\n", *info, mask_str ? mask_str : "");
index dbe886e3d130c776753a41fbd93405621d0a4e52..5c624bdebfb9e86cbe67506e8c8b47ee7ede58d5 100644 (file)
@@ -51,3 +51,18 @@ NTSTATUS can_delete_directory(struct connection_struct *conn,
 {
        return NT_STATUS_OK;
 }
+
+bool change_to_root_user(void)
+{
+       return false;
+}
+
+struct event_context *smbd_event_context(void)
+{
+       return NULL;
+}
+
+struct messaging_context *smbd_messaging_context(void)
+{
+       return NULL;
+}
index 2cd2386c5c011ebef8f0851f5de07306f5e1fa64..9adb2370963e086b6b6a2d61c6322682bbeb4dba 100644 (file)
@@ -128,3 +128,139 @@ NTSTATUS map_nt_error_from_unix(int unix_error)
        /* Default return */
        return NT_STATUS_ACCESS_DENIED;
 }
+
+/* Return a UNIX errno from a NT status code */
+static const struct {
+       NTSTATUS status;
+       int error;
+} nt_errno_map[] = {
+        {NT_STATUS_ACCESS_VIOLATION, EACCES},
+        {NT_STATUS_INVALID_HANDLE, EBADF},
+        {NT_STATUS_ACCESS_DENIED, EACCES},
+        {NT_STATUS_OBJECT_NAME_NOT_FOUND, ENOENT},
+        {NT_STATUS_OBJECT_PATH_NOT_FOUND, ENOENT},
+        {NT_STATUS_SHARING_VIOLATION, EBUSY},
+        {NT_STATUS_OBJECT_PATH_INVALID, ENOTDIR},
+        {NT_STATUS_OBJECT_NAME_COLLISION, EEXIST},
+        {NT_STATUS_PATH_NOT_COVERED, ENOENT},
+       {NT_STATUS_UNSUCCESSFUL, EINVAL},
+       {NT_STATUS_NOT_IMPLEMENTED, ENOSYS},
+       {NT_STATUS_IN_PAGE_ERROR, EFAULT}, 
+       {NT_STATUS_BAD_NETWORK_NAME, ENOENT},
+#ifdef EDQUOT
+       {NT_STATUS_PAGEFILE_QUOTA, EDQUOT},
+       {NT_STATUS_QUOTA_EXCEEDED, EDQUOT},
+       {NT_STATUS_REGISTRY_QUOTA_LIMIT, EDQUOT},
+       {NT_STATUS_LICENSE_QUOTA_EXCEEDED, EDQUOT},
+#endif
+#ifdef ETIME
+       {NT_STATUS_TIMER_NOT_CANCELED, ETIME},
+#endif
+       {NT_STATUS_INVALID_PARAMETER, EINVAL},
+       {NT_STATUS_NO_SUCH_DEVICE, ENODEV},
+       {NT_STATUS_NO_SUCH_FILE, ENOENT},
+#ifdef ENODATA
+       {NT_STATUS_END_OF_FILE, ENODATA}, 
+#endif
+#ifdef ENOMEDIUM
+       {NT_STATUS_NO_MEDIA_IN_DEVICE, ENOMEDIUM}, 
+       {NT_STATUS_NO_MEDIA, ENOMEDIUM},
+#endif
+       {NT_STATUS_NONEXISTENT_SECTOR, ESPIPE}, 
+        {NT_STATUS_NO_MEMORY, ENOMEM},
+       {NT_STATUS_CONFLICTING_ADDRESSES, EADDRINUSE},
+       {NT_STATUS_NOT_MAPPED_VIEW, EINVAL},
+       {NT_STATUS_UNABLE_TO_FREE_VM, EADDRINUSE},
+       {NT_STATUS_ACCESS_DENIED, EACCES}, 
+       {NT_STATUS_BUFFER_TOO_SMALL, ENOBUFS},
+       {NT_STATUS_WRONG_PASSWORD, EACCES},
+       {NT_STATUS_LOGON_FAILURE, EACCES},
+       {NT_STATUS_INVALID_WORKSTATION, EACCES},
+       {NT_STATUS_INVALID_LOGON_HOURS, EACCES},
+       {NT_STATUS_PASSWORD_EXPIRED, EACCES},
+       {NT_STATUS_ACCOUNT_DISABLED, EACCES},
+       {NT_STATUS_DISK_FULL, ENOSPC},
+       {NT_STATUS_INVALID_PIPE_STATE, EPIPE},
+       {NT_STATUS_PIPE_BUSY, EPIPE},
+       {NT_STATUS_PIPE_DISCONNECTED, EPIPE},
+       {NT_STATUS_PIPE_NOT_AVAILABLE, ENOSYS},
+       {NT_STATUS_FILE_IS_A_DIRECTORY, EISDIR},
+       {NT_STATUS_NOT_SUPPORTED, ENOSYS},
+       {NT_STATUS_NOT_A_DIRECTORY, ENOTDIR},
+       {NT_STATUS_DIRECTORY_NOT_EMPTY, ENOTEMPTY},
+       {NT_STATUS_NETWORK_UNREACHABLE, ENETUNREACH},
+       {NT_STATUS_HOST_UNREACHABLE, EHOSTUNREACH},
+       {NT_STATUS_CONNECTION_ABORTED, ECONNABORTED},
+       {NT_STATUS_CONNECTION_REFUSED, ECONNREFUSED},
+       {NT_STATUS_TOO_MANY_LINKS, EMLINK},
+       {NT_STATUS_NETWORK_BUSY, EBUSY},
+       {NT_STATUS_DEVICE_DOES_NOT_EXIST, ENODEV},
+#ifdef ELIBACC
+       {NT_STATUS_DLL_NOT_FOUND, ELIBACC},
+#endif
+       {NT_STATUS_PIPE_BROKEN, EPIPE},
+       {NT_STATUS_REMOTE_NOT_LISTENING, ECONNREFUSED},
+       {NT_STATUS_NETWORK_ACCESS_DENIED, EACCES},
+       {NT_STATUS_TOO_MANY_OPENED_FILES, EMFILE},
+#ifdef EPROTO
+       {NT_STATUS_DEVICE_PROTOCOL_ERROR, EPROTO},
+#endif
+       {NT_STATUS_FLOAT_OVERFLOW, ERANGE},
+       {NT_STATUS_FLOAT_UNDERFLOW, ERANGE},
+       {NT_STATUS_INTEGER_OVERFLOW, ERANGE},
+       {NT_STATUS_MEDIA_WRITE_PROTECTED, EROFS},
+       {NT_STATUS_PIPE_CONNECTED, EISCONN},
+       {NT_STATUS_MEMORY_NOT_ALLOCATED, EFAULT},
+       {NT_STATUS_FLOAT_INEXACT_RESULT, ERANGE},
+       {NT_STATUS_ILL_FORMED_PASSWORD, EACCES},
+       {NT_STATUS_PASSWORD_RESTRICTION, EACCES},
+       {NT_STATUS_ACCOUNT_RESTRICTION, EACCES},
+       {NT_STATUS_PORT_CONNECTION_REFUSED, ECONNREFUSED},
+       {NT_STATUS_NAME_TOO_LONG, ENAMETOOLONG},
+       {NT_STATUS_REMOTE_DISCONNECT, ESHUTDOWN},
+       {NT_STATUS_CONNECTION_DISCONNECTED, ECONNABORTED},
+       {NT_STATUS_CONNECTION_RESET, ENETRESET},
+#ifdef ENOTUNIQ
+       {NT_STATUS_IP_ADDRESS_CONFLICT1, ENOTUNIQ},
+       {NT_STATUS_IP_ADDRESS_CONFLICT2, ENOTUNIQ},
+#endif
+       {NT_STATUS_PORT_MESSAGE_TOO_LONG, EMSGSIZE},
+       {NT_STATUS_PROTOCOL_UNREACHABLE, ENOPROTOOPT},
+       {NT_STATUS_ADDRESS_ALREADY_EXISTS, EADDRINUSE},
+       {NT_STATUS_PORT_UNREACHABLE, EHOSTUNREACH},
+       {NT_STATUS_IO_TIMEOUT, ETIMEDOUT},
+       {NT_STATUS_RETRY, EAGAIN},
+#ifdef ENOTUNIQ
+       {NT_STATUS_DUPLICATE_NAME, ENOTUNIQ},
+#endif
+#ifdef ECOMM
+       {NT_STATUS_NET_WRITE_FAULT, ECOMM},
+#endif
+#ifdef EXDEV
+       {NT_STATUS_NOT_SAME_DEVICE, EXDEV},
+#endif
+       {NT_STATUS(0), 0}
+};
+
+int map_errno_from_nt_status(NTSTATUS status)
+{
+       int i;
+       DEBUG(10,("map_errno_from_nt_status: 32 bit codes: code=%08x\n",
+               NT_STATUS_V(status)));
+
+       /* Status codes without this bit set are not errors */
+
+       if (!(NT_STATUS_V(status) & 0xc0000000)) {
+               return 0;
+       }
+
+       for (i=0;nt_errno_map[i].error;i++) {
+               if (NT_STATUS_V(nt_errno_map[i].status) ==
+                           NT_STATUS_V(status)) {
+                       return nt_errno_map[i].error;
+               }
+       }
+
+       /* for all other cases - a default code */
+       return EINVAL;
+}
index 743711b9672ca73a482767a855c7dc9db439d2a6..c8aa6afdfc131cc08f9f6caf9f9081a5e709a112 100644 (file)
@@ -787,6 +787,7 @@ int ldb_search(struct ldb_context *ldb,
 done:
        if (ret != LDB_SUCCESS) {
                talloc_free(res);
+               res = NULL;
        }
 
        *_res = res;
index 036af32f385afad2a5f37cf68a296e60416925bc..0d66be0eb171a9890da73703db10b970a896cc79 100644 (file)
@@ -47,7 +47,8 @@ WERROR NetFileClose_r(struct libnetapi_ctx *ctx,
                                            r->in.server_name,
                                            r->in.fileid,
                                            &werr);
-       if (!W_ERROR_IS_OK(werr)) {
+       if (!NT_STATUS_IS_OK(status)) {
+               werr = ntstatus_to_werror(status);
                goto done;
        }
 
index 07a6544af16fb95849846bc3f79066451a458ae9..76c0d0be2af7b598763ae5a69e036a072a2f24a1 100644 (file)
@@ -58,6 +58,10 @@ WERROR NetGetDCName_r(struct libnetapi_ctx *ctx,
                                       r->in.domain_name,
                                       (const char **)r->out.buffer,
                                       &werr);
+
+       if (!NT_STATUS_IS_OK(status)) {
+               werr = ntstatus_to_werror(status);
+       }
  done:
 
        return werr;
index 1d0e1810f15bc8395133ce2d3f9e3ac87595ca78..e6aed360647311ea5a1fd61dd9d2615d1dbac25b 100644 (file)
@@ -271,7 +271,8 @@ WERROR NetShareDel_r(struct libnetapi_ctx *ctx,
                                           r->in.net_name,
                                           r->in.reserved,
                                           &werr);
-       if (!W_ERROR_IS_OK(werr)) {
+       if (!NT_STATUS_IS_OK(status)) {
+               werr = ntstatus_to_werror(status);
                goto done;
        }
 
index 7d0c47f331a6e1f8a9750f5d1cf9bc2f68dc390c..fcb87b77befc30490bb0adf70a0474ffc03d5314 100644 (file)
@@ -108,18 +108,18 @@ static void convert_USER_INFO_X_to_samr_user_info21(struct USER_INFO_X *infoX,
                              infoX->usriX_workstations,
                              infoX->usriX_usr_comment,
                              &zero_parameters,
-                             0,
+                             infoX->usriX_user_id,
                              infoX->usriX_primary_group_id,
                              infoX->usriX_flags,
                              fields_present,
                              zero_logon_hours,
-                             0,
-                             0,
+                             infoX->usriX_bad_pw_count,
+                             infoX->usriX_num_logons,
                              infoX->usriX_country_code,
+                             infoX->usriX_code_page,
                              0,
                              0,
-                             0,
-                             0);
+                             infoX->usriX_password_expired);
 }
 
 /****************************************************************
@@ -132,6 +132,7 @@ static NTSTATUS construct_USER_INFO_X(uint32_t level,
        struct USER_INFO_0 *u0 = NULL;
        struct USER_INFO_1 *u1 = NULL;
        struct USER_INFO_2 *u2 = NULL;
+       struct USER_INFO_3 *u3 = NULL;
        struct USER_INFO_1003 *u1003 = NULL;
        struct USER_INFO_1006 *u1006 = NULL;
        struct USER_INFO_1007 *u1007 = NULL;
@@ -193,6 +194,37 @@ static NTSTATUS construct_USER_INFO_X(uint32_t level,
                        uX->usriX_country_code  = u2->usri2_country_code;
                        uX->usriX_code_page     = u2->usri2_code_page;
                        break;
+               case 3:
+                       u3 = (struct USER_INFO_3 *)buffer;
+                       uX->usriX_name          = u3->usri3_name;
+                       uX->usriX_password_age  = u3->usri3_password_age;
+                       uX->usriX_priv          = u3->usri3_priv;
+                       uX->usriX_home_dir      = u3->usri3_home_dir;
+                       uX->usriX_comment       = u3->usri3_comment;
+                       uX->usriX_flags         = u3->usri3_flags;
+                       uX->usriX_script_path   = u3->usri3_script_path;
+                       uX->usriX_auth_flags    = u3->usri3_auth_flags;
+                       uX->usriX_full_name     = u3->usri3_full_name;
+                       uX->usriX_usr_comment   = u3->usri3_usr_comment;
+                       uX->usriX_parms         = u3->usri3_parms;
+                       uX->usriX_workstations  = u3->usri3_workstations;
+                       uX->usriX_last_logon    = u3->usri3_last_logon;
+                       uX->usriX_last_logoff   = u3->usri3_last_logoff;
+                       uX->usriX_acct_expires  = u3->usri3_acct_expires;
+                       uX->usriX_max_storage   = u3->usri3_max_storage;
+                       uX->usriX_units_per_week= u3->usri3_units_per_week;
+                       uX->usriX_logon_hours   = u3->usri3_logon_hours;
+                       uX->usriX_bad_pw_count  = u3->usri3_bad_pw_count;
+                       uX->usriX_num_logons    = u3->usri3_num_logons;
+                       uX->usriX_logon_server  = u3->usri3_logon_server;
+                       uX->usriX_country_code  = u3->usri3_country_code;
+                       uX->usriX_code_page     = u3->usri3_code_page;
+                       uX->usriX_user_id       = u3->usri3_user_id;
+                       uX->usriX_primary_group_id = u3->usri3_primary_group_id;
+                       uX->usriX_profile       = u3->usri3_profile;
+                       uX->usriX_home_dir_drive = u3->usri3_home_dir_drive;
+                       uX->usriX_password_expired = u3->usri3_password_expired;
+                       break;
                case 1003:
                        u1003 = (struct USER_INFO_1003 *)buffer;
                        uX->usriX_password      = u1003->usri1003_password;
@@ -237,7 +269,6 @@ static NTSTATUS construct_USER_INFO_X(uint32_t level,
                        u1053 = (struct USER_INFO_1053 *)buffer;
                        uX->usriX_home_dir_drive = u1053->usri1053_home_dir_drive;
                        break;
-               case 3:
                case 4:
                default:
                        return NT_STATUS_INVALID_INFO_CLASS;
@@ -1753,9 +1784,17 @@ WERROR NetUserSetInfo_r(struct libnetapi_ctx *ctx,
                        user_mask = SAMR_USER_ACCESS_SET_ATTRIBUTES |
                                    SAMR_USER_ACCESS_GET_GROUPS;
                        break;
+               case 3:
+                       user_mask = STD_RIGHT_READ_CONTROL_ACCESS |
+                                   STD_RIGHT_WRITE_DAC_ACCESS |
+                                   SAMR_USER_ACCESS_GET_GROUPS |
+                                   SAMR_USER_ACCESS_SET_PASSWORD |
+                                   SAMR_USER_ACCESS_SET_ATTRIBUTES |
+                                   SAMR_USER_ACCESS_GET_ATTRIBUTES |
+                                   SAMR_USER_ACCESS_SET_LOC_COM;
+                       break;
                case 1:
                case 2:
-               case 3:
                case 4:
                case 21:
                case 22:
index 254f55c86a14f8dce32e062994cb166970a7684f..cafb5a9f624b50d832e9ba1ce84f03726cbc84b4 100644 (file)
 #  define RL_COMPLETION_CAST
 #endif /* HAVE_NEW_LIBREADLINE */
 
+static bool smb_rl_done;
+
+#if HAVE_LIBREADLINE
+/*
+ * MacOS/X does not have rl_done in readline.h, but
+ * readline.so has it
+ */
+extern int rl_done;
+#endif
+
+void smb_readline_done(void)
+{
+       smb_rl_done = true;
+#if HAVE_LIBREADLINE
+       rl_done = 1;
+#endif
+}
+
 /****************************************************************************
  Display the prompt and wait for input. Call callback() regularly
 ****************************************************************************/
@@ -69,7 +87,7 @@ static char *smb_readline_replacement(const char *prompt, void (*callback)(void)
                return NULL;
        }
 
-       while (1) {
+       while (!smb_rl_done) {
                timeout.tv_sec = 5;
                timeout.tv_usec = 0;
 
@@ -87,6 +105,7 @@ static char *smb_readline_replacement(const char *prompt, void (*callback)(void)
                        callback();
                }
        }
+       return NULL;
 }
 
 /****************************************************************************
index 8760a6109a7ba95f30e5c7f2bf7b4c80317baa61..9f5a0c02ba645d831c94589a794b9a60ba4ef2bc 100644 (file)
@@ -55,7 +55,7 @@ void sec_ace_copy(SEC_ACE *ace_dest, SEC_ACE *ace_src)
 ********************************************************************/
 
 void init_sec_ace(SEC_ACE *t, const DOM_SID *sid, enum security_ace_type type,
-                 uint32 mask, uint8 flag)
+                 uint32_t mask, uint8 flag)
 {
        t->type = type;
        t->flags = flag;
index 4965200bc1129f254798f3faf5ba87902a3d416c..52ff067d6ab358936319e729adae33cfef77fd59 100644 (file)
@@ -512,7 +512,7 @@ SEC_DESC_BUF *se_create_child_secdesc(TALLOC_CTX *ctx, SEC_DESC *parent_ctr,
                if (!inherit)
                        continue;
 
-               init_sec_access(&new_ace->access_mask, ace->access_mask);
+               new_ace->access_mask = ace->access_mask;
                init_sec_ace(new_ace, &ace->trustee, ace->type,
                             new_ace->access_mask, new_flags);
 
@@ -546,14 +546,3 @@ SEC_DESC_BUF *se_create_child_secdesc(TALLOC_CTX *ctx, SEC_DESC *parent_ctr,
 
        return sdb;
 }
-
-/*******************************************************************
- Sets up a SEC_ACCESS structure.
-********************************************************************/
-
-void init_sec_access(uint32 *t, uint32 mask)
-{
-       *t = mask;
-}
-
-
index 33f66ca47f5255621b21985f8c68f91210816608..298655e1819ab9df57027dfe5f846eb3083ea12a 100644 (file)
@@ -124,7 +124,7 @@ static bool share_info_db_init(void)
 
 SEC_DESC *get_share_security_default( TALLOC_CTX *ctx, size_t *psize, uint32 def_access)
 {
-       SEC_ACCESS sa;
+       uint32_t sa;
        SEC_ACE ace;
        SEC_ACL *psa = NULL;
        SEC_DESC *psd = NULL;
@@ -132,7 +132,7 @@ SEC_DESC *get_share_security_default( TALLOC_CTX *ctx, size_t *psize, uint32 def
 
        se_map_generic(&spec_access, &file_generic_mapping);
 
-       init_sec_access(&sa, def_access | spec_access );
+       sa = (def_access | spec_access );
        init_sec_ace(&ace, &global_sid_World, SEC_ACE_TYPE_ACCESS_ALLOWED, sa, 0);
 
        if ((psa = make_sec_acl(ctx, NT4_ACL_REVISION, 1, &ace)) != NULL) {
@@ -332,7 +332,7 @@ bool parse_usershare_acl(TALLOC_CTX *ctx, const char *acl_str, SEC_DESC **ppsd)
        }
 
        for (i = 0; i < num_aces; i++) {
-               SEC_ACCESS sa;
+               uint32_t sa;
                uint32 g_access;
                uint32 s_access;
                DOM_SID sid;
@@ -380,7 +380,7 @@ bool parse_usershare_acl(TALLOC_CTX *ctx, const char *acl_str, SEC_DESC **ppsd)
                pacl++; /* Go past any ',' */
 
                se_map_generic(&s_access, &file_generic_mapping);
-               init_sec_access(&sa, g_access | s_access );
+               sa = (g_access | s_access);
                init_sec_ace(&ace_list[i], &sid, type, sa, 0);
        }
 
index 87e70bb95bf1b2eb6475c39c5148ec61b4693255..7e461556b3758fd3e228874aa5d5105d03fa7309 100644 (file)
@@ -30,7 +30,7 @@ extern NT_USER_TOKEN anonymous_token;
 static uint32 check_ace(SEC_ACE *ace, const NT_USER_TOKEN *token, uint32 acc_desired, 
                        NTSTATUS *status)
 {
-       uint32 mask = ace->access_mask;
+       uint32_t mask = ace->access_mask;
 
        /*
         * Inherit only is ignored.
@@ -176,6 +176,24 @@ void se_map_generic(uint32 *access_mask, const struct generic_mapping *mapping)
        }
 }
 
+/* Map generic access rights to object specific rights for all the ACE's
+ * in a security_acl.
+ */
+
+void security_acl_map_generic(struct security_acl *sa,
+                               const struct generic_mapping *mapping)
+{
+       unsigned int i;
+
+       if (!sa) {
+               return;
+       }
+
+       for (i = 0; i < sa->num_aces; i++) {
+               se_map_generic(&sa->aces[i].access_mask, mapping);
+       }
+}
+
 /* Map standard access rights to object specific rights.  This technique is
    used to give meaning to assigning read, write, execute and all access to
    objects.  Each type of object has its own mapping of standard to object
@@ -328,7 +346,6 @@ NTSTATUS samr_make_sam_obj_sd(TALLOC_CTX *ctx, SEC_DESC **psd, size_t *sd_size)
        DOM_SID act_sid;
 
        SEC_ACE ace[3];
-       SEC_ACCESS mask;
 
        SEC_ACL *psa = NULL;
 
@@ -339,13 +356,14 @@ NTSTATUS samr_make_sam_obj_sd(TALLOC_CTX *ctx, SEC_DESC **psd, size_t *sd_size)
        sid_append_rid(&act_sid, BUILTIN_ALIAS_RID_ACCOUNT_OPS);
 
        /*basic access for every one*/
-       init_sec_access(&mask, GENERIC_RIGHTS_SAM_EXECUTE | GENERIC_RIGHTS_SAM_READ);
-       init_sec_ace(&ace[0], &global_sid_World, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
+       init_sec_ace(&ace[0], &global_sid_World, SEC_ACE_TYPE_ACCESS_ALLOWED,
+               GENERIC_RIGHTS_SAM_EXECUTE | GENERIC_RIGHTS_SAM_READ, 0);
 
        /*full access for builtin aliases Administrators and Account Operators*/
-       init_sec_access(&mask, GENERIC_RIGHTS_SAM_ALL_ACCESS);
-       init_sec_ace(&ace[1], &adm_sid, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
-       init_sec_ace(&ace[2], &act_sid, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
+       init_sec_ace(&ace[1], &adm_sid,
+               SEC_ACE_TYPE_ACCESS_ALLOWED, GENERIC_RIGHTS_SAM_ALL_ACCESS, 0);
+       init_sec_ace(&ace[2], &act_sid,
+               SEC_ACE_TYPE_ACCESS_ALLOWED, GENERIC_RIGHTS_SAM_ALL_ACCESS, 0);
 
        if ((psa = make_sec_acl(ctx, NT4_ACL_REVISION, 3, ace)) == NULL)
                return NT_STATUS_NO_MEMORY;
index 8c3389eb9b6a65ba1c37c78bee79ad6bb7ef022d..5530290c57a5126c06d1ee456d78e846336de217 100644 (file)
@@ -252,6 +252,7 @@ void dns_unmarshall_domain_name(TALLOC_CTX *mem_ctx,
 
        if (!(name = talloc(mem_ctx, struct dns_domain_name))) {
                buf->error = ERROR_DNS_NO_MEMORY;
+               return;
        }
 
        dns_unmarshall_label(name, 0, buf, &name->pLabelList);
index 500cbd6681a41ad2c1cd4211daabe6c3d744acef..559c2644d44a1ef3d5fb37b4797184d80e446cd0 100644 (file)
@@ -378,10 +378,10 @@ DNS_ERROR dns_create_update_request(TALLOC_CTX *mem_ctx,
        if (!ERR_DNS_IS_OK(err)) return err;
 
        /*
-        * The zone must be used at all
+        * Use the same prereq as WinXP -- No CNAME records for this host.
         */
 
-       err = dns_create_rrec(req, domainname, QTYPE_ANY, DNS_CLASS_ANY,
+       err = dns_create_rrec(req, hostname, QTYPE_CNAME, DNS_CLASS_NONE,
                              0, 0, NULL, &rec);
        if (!ERR_DNS_IS_OK(err)) goto error;
 
index edabbed0e93bdda6ab91620dcc9379fa8a87fa95..c37220c9030a6669e427a9a54bb6eb9bac10cc05 100644 (file)
@@ -283,7 +283,7 @@ bool ads_cldap_netlogon_5(TALLOC_CTX *mem_ctx,
                return false;
        }
 
-       *reply5 = reply->nt5_ex;
+       *reply5 = reply->data.nt5_ex;
 
        return true;
 }
index bfcfcf30b98ff8754f67325c09a1269e68fb6c7c..40f052281ddf28e8cf02c5030279a723d2355395 100644 (file)
@@ -2828,6 +2828,7 @@ ADS_STATUS ads_domain_func_level(ADS_STRUCT *ads, uint32 *val)
                if ( (ads_s = ads_init( ads->server.realm, ads->server.workgroup, 
                        ads->server.ldap_server )) == NULL )
                {
+                       status = ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
                        goto done;
                }
                ads_s->auth.flags = ADS_AUTH_ANON_BIND;
index 72f5dee80cb1782770de3ea25d871917d39bfbb4..d23c36f3269fc2bb4e0b72c362bedd0a10df5adb 100644 (file)
@@ -86,6 +86,8 @@ ADS_STATUS ads_guess_service_principal(ADS_STRUCT *ads,
                server_realm = SMB_STRDUP(ads->config.realm);
 
                if (!server || !server_realm) {
+                       SAFE_FREE(server);
+                       SAFE_FREE(server_realm);
                        return ADS_ERROR(LDAP_NO_MEMORY);
                }
 
index c07407c3f0bbf3fddf835a6c7ea3dbe27b967cbb..02c3abaa1ea9e8a457f448bfec1ca7441d61760d 100644 (file)
@@ -93,7 +93,7 @@ static NTSTATUS generate_gp_registry_entry(TALLOC_CTX *mem_ctx,
        data->type = data_type;
        switch (data->type) {
                case REG_QWORD:
-                       data->v.qword = (uint64_t)data_p;
+                       data->v.qword = *(uint64_t *)data_p;
                        break;
                case REG_SZ:
                        data->v.sz.str = talloc_strdup(mem_ctx, (char *)data_p);
diff --git a/source3/libgpo/gpext/security.c b/source3/libgpo/gpext/security.c
new file mode 100644 (file)
index 0000000..1d746da
--- /dev/null
@@ -0,0 +1,267 @@
+/*
+ *  Unix SMB/CIFS implementation.
+ *  Group Policy Support
+ *  Copyright (C) Guenther Deschner 2005-2008
+ *
+ *  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 "libgpo/gpo_ini.h"
+
+#define GP_EXT_NAME "security"
+
+#define GPTTMPL_UNIX_PATH  "Microsoft/Windows NT/SecEdit/GptTmpl.inf"
+
+#define GPTTMPL_SECTION_UNICODE                        "Unicode"
+#define GPTTMPL_SECTION_VERSION                        "Version"
+
+#define GPTTMPL_SECTION_REGISTRY_VALUES                "Registry Values"
+#define GPTTMPL_SECTION_SYSTEM_ACCESS          "System Access"
+#define GPTTMPL_SECTION_KERBEROS_POLICY                "Kerberos Policy"
+#define GPTTMPL_SECTION_EVENT_AUDIT            "Event Audit"
+#define GPTTMPL_SECTION_PRIVILEGE_RIGHTS       "Privilege Rights"
+#define GPTTMPL_SECTION_APPLICATION_LOG                "Application Log"
+#define GPTTMPL_SECTION_SECURITY_LOG           "Security Log"
+#define GPTTMPL_SECTION_SYSTEM_LOG             "System Log"
+#define GPTTMPL_SECTION_GROUP_MEMBERSHIP       "Group Membership"
+#define GPTTMPL_SECTION_FILE_SECURITY          "File Security"
+#define GPTTMPL_SECTION_SERVICE_GENERAL_SETTING "Service General Setting"
+
+static TALLOC_CTX *ctx = NULL;
+
+struct gpttmpl_table {
+       const char *section;
+       const char *parameter;
+       enum winreg_Type type;
+};
+
+/****************************************************************
+ parse the Version section from gpttmpl file
+****************************************************************/
+
+#define GPTTMPL_PARAMETER_REVISION "Revision"
+#define GPTTMPL_PARAMETER_SIGNATURE "signature"
+#define GPTTMPL_VALUE_CHICAGO "$CHICAGO$" /* whatever this is good for... */
+#define GPTTMPL_PARAMETER_UNICODE "Unicode"
+
+static NTSTATUS gpttmpl_parse_header(dictionary *dict,
+                                    uint32_t *version_out)
+{
+       const char *signature = NULL;
+       uint32_t version;
+
+       if (!dict) {
+               return NT_STATUS_INVALID_PARAMETER;
+       }
+
+       if ((signature = iniparser_getstring(dict, GPTTMPL_SECTION_VERSION
+                       ":"GPTTMPL_PARAMETER_SIGNATURE, NULL)) == NULL) {
+               return NT_STATUS_INTERNAL_DB_CORRUPTION;
+       }
+
+       if (!strequal(signature, GPTTMPL_VALUE_CHICAGO)) {
+               return NT_STATUS_INTERNAL_DB_CORRUPTION;
+       }
+
+       if ((version = iniparser_getint(dict, GPTTMPL_SECTION_VERSION
+                       ":"GPTTMPL_PARAMETER_REVISION, Undefined)) == Undefined) {
+               return NT_STATUS_INTERNAL_DB_CORRUPTION;
+       }
+
+       if (version_out) {
+               *version_out = version;
+       }
+
+       /* treat that as boolean */
+       if ((!iniparser_getboolean(dict, GPTTMPL_SECTION_UNICODE
+                       ":"GPTTMPL_PARAMETER_UNICODE, Undefined)) == Undefined) {
+               return NT_STATUS_INTERNAL_DB_CORRUPTION;
+       }
+
+       return NT_STATUS_OK;
+}
+
+/****************************************************************
+****************************************************************/
+
+static NTSTATUS gpttmpl_init_context(TALLOC_CTX *mem_ctx,
+                                    uint32_t flags,
+                                    const char *unix_path,
+                                    struct gp_inifile_context **ini_ctx)
+{
+       NTSTATUS status;
+       uint32_t version;
+       struct gp_inifile_context *tmp_ctx = NULL;
+
+       status = gp_inifile_init_context(mem_ctx, flags, unix_path,
+                                        GPTTMPL_UNIX_PATH, &tmp_ctx);
+       NT_STATUS_NOT_OK_RETURN(status);
+
+       status = gpttmpl_parse_header(tmp_ctx->dict, &version);
+       if (!NT_STATUS_IS_OK(status)) {
+               DEBUG(1,("gpttmpl_init_context: failed: %s\n",
+                       nt_errstr(status)));
+               TALLOC_FREE(tmp_ctx);
+               return status;
+       }
+
+       *ini_ctx = tmp_ctx;
+
+       return NT_STATUS_OK;
+}
+
+/****************************************************************
+****************************************************************/
+
+static NTSTATUS gpttmpl_process(struct gp_inifile_context *ini_ctx,
+                               struct registry_key *root_key,
+                               uint32_t flags)
+{
+       return NT_STATUS_OK;
+}
+
+/****************************************************************
+****************************************************************/
+
+static NTSTATUS security_process_group_policy(ADS_STRUCT *ads,
+                                             TALLOC_CTX *mem_ctx,
+                                             uint32_t flags,
+                                             struct registry_key *root_key,
+                                             const struct nt_user_token *token,
+                                             struct GROUP_POLICY_OBJECT *gpo,
+                                             const char *extension_guid,
+                                             const char *snapin_guid)
+{
+       NTSTATUS status;
+       char *unix_path = NULL;
+       struct gp_inifile_context *ini_ctx = NULL;
+
+       debug_gpext_header(0, "security_process_group_policy", flags, gpo,
+                          extension_guid, snapin_guid);
+
+       /* this handler processes the gpttmpl files and merge output to the
+        * registry */
+
+       status = gpo_get_unix_path(mem_ctx, gpo, &unix_path);
+       if (!NT_STATUS_IS_OK(status)) {
+               goto out;
+       }
+
+       status = gpttmpl_init_context(mem_ctx, flags, unix_path, &ini_ctx);
+       if (!NT_STATUS_IS_OK(status)) {
+               goto out;
+       }
+
+       status = gpttmpl_process(ini_ctx, root_key, flags);
+       if (!NT_STATUS_IS_OK(status)) {
+               goto out;
+       }
+
+ out:
+       if (!NT_STATUS_IS_OK(status)) {
+               DEBUG(0,("security_process_group_policy: %s\n",
+                       nt_errstr(status)));
+       }
+       TALLOC_FREE(ini_ctx);
+
+       return status;
+}
+
+/****************************************************************
+****************************************************************/
+
+static NTSTATUS security_get_reg_config(TALLOC_CTX *mem_ctx,
+                                       struct gp_extension_reg_info **reg_info)
+{
+       NTSTATUS status;
+       struct gp_extension_reg_info *info = NULL;
+
+       struct gp_extension_reg_table table[] = {
+               /* FIXME: how can we store the "(Default)" value ??? */
+               /* { "", REG_SZ, "Security" }, */
+               { "ProcessGroupPolicy", REG_SZ, "security_process_group_policy" },
+               { "NoUserPolicy", REG_DWORD, "1" },
+               { "ExtensionDebugLevel", REG_DWORD, "1" },
+               { NULL, REG_NONE, NULL }
+       };
+
+       info = TALLOC_ZERO_P(mem_ctx, struct gp_extension_reg_info);
+       NT_STATUS_HAVE_NO_MEMORY(info);
+
+       status = gp_ext_info_add_entry(mem_ctx, GP_EXT_NAME,
+                                      GP_EXT_GUID_SECURITY,
+                                      table, info);
+       NT_STATUS_NOT_OK_RETURN(status);
+
+       *reg_info = info;
+
+       return NT_STATUS_OK;
+}
+
+
+/****************************************************************
+****************************************************************/
+
+static NTSTATUS security_initialize(TALLOC_CTX *mem_ctx)
+{
+       return NT_STATUS_OK;
+}
+
+/****************************************************************
+****************************************************************/
+
+static NTSTATUS security_shutdown(void)
+{
+       NTSTATUS status;
+
+       status = unregister_gp_extension(GP_EXT_NAME);
+       if (NT_STATUS_IS_OK(status)) {
+               return status;
+       }
+
+       TALLOC_FREE(ctx);
+
+       return NT_STATUS_OK;
+}
+
+/****************************************************************
+****************************************************************/
+
+static struct gp_extension_methods security_methods = {
+       .initialize             = security_initialize,
+       .process_group_policy   = security_process_group_policy,
+       .get_reg_config         = security_get_reg_config,
+       .shutdown               = security_shutdown
+};
+
+/****************************************************************
+****************************************************************/
+
+static NTSTATUS gpext_security_init(void)
+{
+       NTSTATUS status;
+
+       ctx = talloc_init("gpext_security_init");
+       NT_STATUS_HAVE_NO_MEMORY(ctx);
+
+       status = register_gp_extension(ctx, SMB_GPEXT_INTERFACE_VERSION,
+                                      GP_EXT_NAME, GP_EXT_GUID_SECURITY,
+                                      &security_methods);
+       if (!NT_STATUS_IS_OK(status)) {
+               TALLOC_FREE(ctx);
+       }
+
+       return status;
+}
index 920deeb189b54aef09011952be23e45c9e92fabf..d49315021e4eccb8cb3c6184f5cbaa524e7902ce 100644 (file)
@@ -689,25 +689,25 @@ static WERROR gp_reg_generate_sd(TALLOC_CTX *mem_ctx,
                                 size_t *sd_size)
 {
        SEC_ACE ace[6];
-       SEC_ACCESS mask;
+       uint32_t mask;
 
        SEC_ACL *acl = NULL;
 
        uint8_t inherit_flags;
 
-       init_sec_access(&mask, REG_KEY_ALL);
+       mask = REG_KEY_ALL;
        init_sec_ace(&ace[0],
                     &global_sid_System,
                     SEC_ACE_TYPE_ACCESS_ALLOWED,
                     mask, 0);
 
-       init_sec_access(&mask, REG_KEY_ALL);
+       mask = REG_KEY_ALL;
        init_sec_ace(&ace[1],
                     &global_sid_Builtin_Administrators,
                     SEC_ACE_TYPE_ACCESS_ALLOWED,
                     mask, 0);
 
-       init_sec_access(&mask, REG_KEY_READ);
+       mask = REG_KEY_READ;
        init_sec_ace(&ace[2],
                     sid ? sid : &global_sid_Authenticated_Users,
                     SEC_ACE_TYPE_ACCESS_ALLOWED,
@@ -717,19 +717,19 @@ static WERROR gp_reg_generate_sd(TALLOC_CTX *mem_ctx,
                        SEC_ACE_FLAG_CONTAINER_INHERIT |
                        SEC_ACE_FLAG_INHERIT_ONLY;
 
-       init_sec_access(&mask, REG_KEY_ALL);
+       mask = REG_KEY_ALL;
        init_sec_ace(&ace[3],
                     &global_sid_System,
                     SEC_ACE_TYPE_ACCESS_ALLOWED,
                     mask, inherit_flags);
 
-       init_sec_access(&mask, REG_KEY_ALL);
+       mask = REG_KEY_ALL;
        init_sec_ace(&ace[4],
                     &global_sid_Builtin_Administrators,
                     SEC_ACE_TYPE_ACCESS_ALLOWED,
                     mask, inherit_flags);
 
-       init_sec_access(&mask, REG_KEY_READ);
+       mask = REG_KEY_READ;
        init_sec_ace(&ace[5],
                     sid ? sid : &global_sid_Authenticated_Users,
                     SEC_ACE_TYPE_ACCESS_ALLOWED,
index a39dee676fc7b0cb1706f4d409d21bcc3f71bb18..ab8af0be6bec6d1a3b75be613d3e04ef2257d54a 100644 (file)
@@ -357,10 +357,15 @@ static ADS_STATUS libnet_join_set_machine_spn(TALLOC_CTX *mem_ctx,
        strupper_m(spn);
        spn_array[0] = spn;
 
-       if (name_to_fqdn(my_fqdn, r->in.machine_name) &&
-           !strequal(my_fqdn, r->in.machine_name)) {
+       if (!name_to_fqdn(my_fqdn, r->in.machine_name)
+           || (strchr(my_fqdn, '.') == NULL)) {
+               fstr_sprintf(my_fqdn, "%s.%s", r->in.machine_name,
+                            r->out.dns_domain_name);
+       }
+
+       strlower_m(my_fqdn);
 
-               strlower_m(my_fqdn);
+       if (!strequal(my_fqdn, r->in.machine_name)) {
                spn = talloc_asprintf(mem_ctx, "HOST/%s", my_fqdn);
                if (!spn) {
                        return ADS_ERROR_LDAP(LDAP_NO_MEMORY);
index 43046a44c0cd2903cc45690f26d6b489d675d5a4..69a16c1c7d4380bcada5a686e985d633bd14ff75 100644 (file)
@@ -53,7 +53,7 @@ krb5_error_code libnet_keytab_add(struct libnet_keytab_context *ctx);
 
 struct libnet_keytab_entry *libnet_keytab_search(struct libnet_keytab_context *ctx,
                                                 const char *principal, int kvno,
-                                                const const krb5_enctype enctype,
+                                                const krb5_enctype enctype,
                                                 TALLOC_CTX *mem_ctx);
 #endif
 
index 264b00b84fe44d5255eaae05131420b792c2de42..4b872d7936e82dbb46913423bda15f0e38980087 100644 (file)
@@ -391,7 +391,7 @@ struct nbt_dgram_packet {
 }/* [public,flag(LIBNDR_FLAG_NOALIGN|LIBNDR_FLAG_BIGENDIAN|LIBNDR_PRINT_ARRAY_HEX)] */;
 
 struct nbt_sockaddr {
-       uint32_t sa_family;
+       uint32_t sockaddr_family;
        const char * pdc_ip;/* [flag(LIBNDR_FLAG_BIGENDIAN)] */
        DATA_BLOB remaining;/* [flag(LIBNDR_FLAG_REMAINING)] */
 }/* [gensize,public] */;
index 84cfabda574a3a58e456081dda4c6f5a3edaa44d..c02b539da52708f310af440c33d581b82de5f25c 100644 (file)
@@ -1531,7 +1531,7 @@ _PUBLIC_ enum ndr_err_code ndr_push_nbt_sockaddr(struct ndr_push *ndr, int ndr_f
 {
        if (ndr_flags & NDR_SCALARS) {
                NDR_CHECK(ndr_push_align(ndr, 4));
-               NDR_CHECK(ndr_push_uint32(ndr, NDR_SCALARS, r->sa_family));
+               NDR_CHECK(ndr_push_uint32(ndr, NDR_SCALARS, r->sockaddr_family));
                {
                        uint32_t _flags_save_ipv4address = ndr->flags;
                        ndr_set_flags(&ndr->flags, LIBNDR_FLAG_BIGENDIAN);
@@ -1554,7 +1554,7 @@ _PUBLIC_ enum ndr_err_code ndr_pull_nbt_sockaddr(struct ndr_pull *ndr, int ndr_f
 {
        if (ndr_flags & NDR_SCALARS) {
                NDR_CHECK(ndr_pull_align(ndr, 4));
-               NDR_CHECK(ndr_pull_uint32(ndr, NDR_SCALARS, &r->sa_family));
+               NDR_CHECK(ndr_pull_uint32(ndr, NDR_SCALARS, &r->sockaddr_family));
                {
                        uint32_t _flags_save_ipv4address = ndr->flags;
                        ndr_set_flags(&ndr->flags, LIBNDR_FLAG_BIGENDIAN);
@@ -1577,7 +1577,7 @@ _PUBLIC_ void ndr_print_nbt_sockaddr(struct ndr_print *ndr, const char *name, co
 {
        ndr_print_struct(ndr, name, "nbt_sockaddr");
        ndr->depth++;
-       ndr_print_uint32(ndr, "sa_family", r->sa_family);
+       ndr_print_uint32(ndr, "sockaddr_family", r->sockaddr_family);
        ndr_print_ipv4address(ndr, "pdc_ip", r->pdc_ip);
        ndr_print_DATA_BLOB(ndr, "remaining", r->remaining);
        ndr->depth--;
index 82571d96e67ad09cc8bb4efe2376c96796fa72bf..f3590fcf2bc8f79d8457ece5b1def40661c3372a 100644 (file)
@@ -339,7 +339,7 @@ interface nbt
         */
 
        typedef [public,gensize] struct {
-               uint32                  sa_family;
+               uint32                  sockaddr_family;
                [flag(NDR_BIG_ENDIAN)]  ipv4address pdc_ip;
                [flag(NDR_REMAINING)]   DATA_BLOB remaining;
        } nbt_sockaddr;
index fb35ecbe1fb6c1680ad1890f2162afc6206eec9e..68495076b636b34df260c2b85a33ad2792153116 100644 (file)
@@ -924,7 +924,7 @@ static void cli_state_handler(struct event_context *event_ctx,
                }
                cli->evt_inbuf = tmp;
 
-               res = recv(cli->fd, cli->evt_inbuf + old_size, available, 0);
+               res = sys_recv(cli->fd, cli->evt_inbuf + old_size, available, 0);
                if (res == -1) {
                        DEBUG(10, ("recv failed: %s\n", strerror(errno)));
                        status = map_nt_error_from_unix(errno);
@@ -970,7 +970,7 @@ static void cli_state_handler(struct event_context *event_ctx,
                        return;
                }
 
-               sent = send(cli->fd, req->outbuf + req->sent,
+               sent = sys_send(cli->fd, req->outbuf + req->sent,
                            to_send - req->sent, 0);
 
                if (sent < 0) {
index e8799bce4794602c41520a3cc8a4801fcb6ebb66..611ae0870c4f2bf6e8eb3a683dea3f8e87d1b364 100644 (file)
@@ -279,8 +279,8 @@ bool receive_getdc_response(TALLOC_CTX *mem_ctx,
        /* do we still need this ? */
        *nt_version = r.ntver;
 
-       returned_domain = r.nt5_ex.domain;
-       returned_dc = r.nt5_ex.pdc_name;
+       returned_domain = r.data.nt5_ex.domain;
+       returned_dc = r.data.nt5_ex.pdc_name;
 
        if (!strequal(returned_domain, domain_name)) {
                DEBUG(3, ("GetDC: Expected domain %s, got %s\n",
index 36746419f7a0ab1c0d7c9888bf5ba49a3f8697d8..54f8a7a43cecc1ad4ea69855d002ea61c140ae20 100644 (file)
@@ -236,142 +236,6 @@ void cli_dos_error(struct cli_state *cli, uint8 *eclass, uint32 *ecode)
        *ecode  = SVAL(cli->inbuf,smb_err);
 }
 
-/* Return a UNIX errno from a NT status code */
-static const struct {
-       NTSTATUS status;
-       int error;
-} nt_errno_map[] = {
-        {NT_STATUS_ACCESS_VIOLATION, EACCES},
-        {NT_STATUS_INVALID_HANDLE, EBADF},
-        {NT_STATUS_ACCESS_DENIED, EACCES},
-        {NT_STATUS_OBJECT_NAME_NOT_FOUND, ENOENT},
-        {NT_STATUS_OBJECT_PATH_NOT_FOUND, ENOENT},
-        {NT_STATUS_SHARING_VIOLATION, EBUSY},
-        {NT_STATUS_OBJECT_PATH_INVALID, ENOTDIR},
-        {NT_STATUS_OBJECT_NAME_COLLISION, EEXIST},
-        {NT_STATUS_PATH_NOT_COVERED, ENOENT},
-       {NT_STATUS_UNSUCCESSFUL, EINVAL},
-       {NT_STATUS_NOT_IMPLEMENTED, ENOSYS},
-       {NT_STATUS_IN_PAGE_ERROR, EFAULT}, 
-       {NT_STATUS_BAD_NETWORK_NAME, ENOENT},
-#ifdef EDQUOT
-       {NT_STATUS_PAGEFILE_QUOTA, EDQUOT},
-       {NT_STATUS_QUOTA_EXCEEDED, EDQUOT},
-       {NT_STATUS_REGISTRY_QUOTA_LIMIT, EDQUOT},
-       {NT_STATUS_LICENSE_QUOTA_EXCEEDED, EDQUOT},
-#endif
-#ifdef ETIME
-       {NT_STATUS_TIMER_NOT_CANCELED, ETIME},
-#endif
-       {NT_STATUS_INVALID_PARAMETER, EINVAL},
-       {NT_STATUS_NO_SUCH_DEVICE, ENODEV},
-       {NT_STATUS_NO_SUCH_FILE, ENOENT},
-#ifdef ENODATA
-       {NT_STATUS_END_OF_FILE, ENODATA}, 
-#endif
-#ifdef ENOMEDIUM
-       {NT_STATUS_NO_MEDIA_IN_DEVICE, ENOMEDIUM}, 
-       {NT_STATUS_NO_MEDIA, ENOMEDIUM},
-#endif
-       {NT_STATUS_NONEXISTENT_SECTOR, ESPIPE}, 
-        {NT_STATUS_NO_MEMORY, ENOMEM},
-       {NT_STATUS_CONFLICTING_ADDRESSES, EADDRINUSE},
-       {NT_STATUS_NOT_MAPPED_VIEW, EINVAL},
-       {NT_STATUS_UNABLE_TO_FREE_VM, EADDRINUSE},
-       {NT_STATUS_ACCESS_DENIED, EACCES}, 
-       {NT_STATUS_BUFFER_TOO_SMALL, ENOBUFS},
-       {NT_STATUS_WRONG_PASSWORD, EACCES},
-       {NT_STATUS_LOGON_FAILURE, EACCES},
-       {NT_STATUS_INVALID_WORKSTATION, EACCES},
-       {NT_STATUS_INVALID_LOGON_HOURS, EACCES},
-       {NT_STATUS_PASSWORD_EXPIRED, EACCES},
-       {NT_STATUS_ACCOUNT_DISABLED, EACCES},
-       {NT_STATUS_DISK_FULL, ENOSPC},
-       {NT_STATUS_INVALID_PIPE_STATE, EPIPE},
-       {NT_STATUS_PIPE_BUSY, EPIPE},
-       {NT_STATUS_PIPE_DISCONNECTED, EPIPE},
-       {NT_STATUS_PIPE_NOT_AVAILABLE, ENOSYS},
-       {NT_STATUS_FILE_IS_A_DIRECTORY, EISDIR},
-       {NT_STATUS_NOT_SUPPORTED, ENOSYS},
-       {NT_STATUS_NOT_A_DIRECTORY, ENOTDIR},
-       {NT_STATUS_DIRECTORY_NOT_EMPTY, ENOTEMPTY},
-       {NT_STATUS_NETWORK_UNREACHABLE, ENETUNREACH},
-       {NT_STATUS_HOST_UNREACHABLE, EHOSTUNREACH},
-       {NT_STATUS_CONNECTION_ABORTED, ECONNABORTED},
-       {NT_STATUS_CONNECTION_REFUSED, ECONNREFUSED},
-       {NT_STATUS_TOO_MANY_LINKS, EMLINK},
-       {NT_STATUS_NETWORK_BUSY, EBUSY},
-       {NT_STATUS_DEVICE_DOES_NOT_EXIST, ENODEV},
-#ifdef ELIBACC
-       {NT_STATUS_DLL_NOT_FOUND, ELIBACC},
-#endif
-       {NT_STATUS_PIPE_BROKEN, EPIPE},
-       {NT_STATUS_REMOTE_NOT_LISTENING, ECONNREFUSED},
-       {NT_STATUS_NETWORK_ACCESS_DENIED, EACCES},
-       {NT_STATUS_TOO_MANY_OPENED_FILES, EMFILE},
-#ifdef EPROTO
-       {NT_STATUS_DEVICE_PROTOCOL_ERROR, EPROTO},
-#endif
-       {NT_STATUS_FLOAT_OVERFLOW, ERANGE},
-       {NT_STATUS_FLOAT_UNDERFLOW, ERANGE},
-       {NT_STATUS_INTEGER_OVERFLOW, ERANGE},
-       {NT_STATUS_MEDIA_WRITE_PROTECTED, EROFS},
-       {NT_STATUS_PIPE_CONNECTED, EISCONN},
-       {NT_STATUS_MEMORY_NOT_ALLOCATED, EFAULT},
-       {NT_STATUS_FLOAT_INEXACT_RESULT, ERANGE},
-       {NT_STATUS_ILL_FORMED_PASSWORD, EACCES},
-       {NT_STATUS_PASSWORD_RESTRICTION, EACCES},
-       {NT_STATUS_ACCOUNT_RESTRICTION, EACCES},
-       {NT_STATUS_PORT_CONNECTION_REFUSED, ECONNREFUSED},
-       {NT_STATUS_NAME_TOO_LONG, ENAMETOOLONG},
-       {NT_STATUS_REMOTE_DISCONNECT, ESHUTDOWN},
-       {NT_STATUS_CONNECTION_DISCONNECTED, ECONNABORTED},
-       {NT_STATUS_CONNECTION_RESET, ENETRESET},
-#ifdef ENOTUNIQ
-       {NT_STATUS_IP_ADDRESS_CONFLICT1, ENOTUNIQ},
-       {NT_STATUS_IP_ADDRESS_CONFLICT2, ENOTUNIQ},
-#endif
-       {NT_STATUS_PORT_MESSAGE_TOO_LONG, EMSGSIZE},
-       {NT_STATUS_PROTOCOL_UNREACHABLE, ENOPROTOOPT},
-       {NT_STATUS_ADDRESS_ALREADY_EXISTS, EADDRINUSE},
-       {NT_STATUS_PORT_UNREACHABLE, EHOSTUNREACH},
-       {NT_STATUS_IO_TIMEOUT, ETIMEDOUT},
-       {NT_STATUS_RETRY, EAGAIN},
-#ifdef ENOTUNIQ
-       {NT_STATUS_DUPLICATE_NAME, ENOTUNIQ},
-#endif
-#ifdef ECOMM
-       {NT_STATUS_NET_WRITE_FAULT, ECOMM},
-#endif
-#ifdef EXDEV
-       {NT_STATUS_NOT_SAME_DEVICE, EXDEV},
-#endif
-       {NT_STATUS(0), 0}
-};
-
-/****************************************************************************
- The following mappings need tidying up and moving into libsmb/errormap.c...
-****************************************************************************/
-
-static int cli_errno_from_nt(NTSTATUS status)
-{
-       int i;
-        DEBUG(10,("cli_errno_from_nt: 32 bit codes: code=%08x\n", NT_STATUS_V(status)));
-
-        /* Status codes without this bit set are not errors */
-
-        if (!(NT_STATUS_V(status) & 0xc0000000)) {
-                return 0;
-       }
-
-       for (i=0;nt_errno_map[i].error;i++) {
-               if (NT_STATUS_V(nt_errno_map[i].status) ==
-                   NT_STATUS_V(status)) return nt_errno_map[i].error;
-       }
-
-        /* for all other cases - a default code */
-        return EINVAL;
-}
 
 /* Return a UNIX errno appropriate for the error received in the last
    packet. */
@@ -382,7 +246,7 @@ int cli_errno(struct cli_state *cli)
 
        if (cli_is_nt_error(cli)) {
                status = cli_nt_error(cli);
-               return cli_errno_from_nt(status);
+               return map_errno_from_nt_status(status);
        }
 
         if (cli_is_dos_error(cli)) {
@@ -391,7 +255,7 @@ int cli_errno(struct cli_state *cli)
 
                 cli_dos_error(cli, &eclass, &ecode);
                status = dos_to_ntstatus(eclass, ecode);
-               return cli_errno_from_nt(status);
+               return map_errno_from_nt_status(status);
         }
 
         /*
index f369d28dff4a645a5925a78aaa3d817c2f33281f..dcdfec241d915b5694895fe5a5f5775d395ecbbd 100644 (file)
@@ -2,17 +2,17 @@
    Unix SMB/CIFS implementation.
    client quota functions
    Copyright (C) Stefan (metze) Metzmacher     2003
-   
+
    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/>.
 */
@@ -25,7 +25,7 @@ bool cli_get_quota_handle(struct cli_state *cli, int *quota_fnum)
                 0x00000016, DESIRED_ACCESS_PIPE,
                 0x00000000, FILE_SHARE_READ|FILE_SHARE_WRITE,
                 FILE_OPEN, 0x00000000, 0x03);
-                
+
        if (*quota_fnum == (-1)) {
                return False;
        }
@@ -37,7 +37,7 @@ void free_ntquota_list(SMB_NTQUOTA_LIST **qt_list)
 {
        if (!qt_list)
                return;
-               
+
        if ((*qt_list)->mem_ctx)
                talloc_destroy((*qt_list)->mem_ctx);
 
@@ -60,7 +60,7 @@ static bool parse_user_quota_record(const char *rdata, unsigned int rdata_count,
        if (rdata_count < 40) {
                return False;
        }
-               
+
        /* offset to next quota record.
         * 4 bytes IVAL(rdata,0)
         * unused here...
@@ -116,7 +116,7 @@ static bool parse_user_quota_record(const char *rdata, unsigned int rdata_count,
                return False;
        }
 #endif /* LARGE_SMB_OFF_T */
-       
+
        sid_parse(rdata+40,sid_len,&qt.sid);
 
        qt.qtype = SMB_USER_QUOTA_TYPE;
@@ -149,13 +149,13 @@ bool cli_get_user_quota(struct cli_state *cli, int quota_fnum, SMB_NTQUOTA_STRUC
        SIVAL(params, 4,0x00000024);
        SIVAL(params, 8,0x00000000);
        SIVAL(params,12,0x00000024);
-       
+
        sid_len = ndr_size_dom_sid(&pqt->sid, 0);
        data_len = sid_len+8;
        SIVAL(data, 0, 0x00000000);
        SIVAL(data, 4, sid_len);
        sid_linearize(data+8, sid_len, &pqt->sid);
-       
+
        if (!cli_send_nt_trans(cli, 
                               NT_TRANSACT_GET_USER_QUOTA, 
                               0, 
@@ -204,7 +204,7 @@ bool cli_set_user_quota(struct cli_state *cli, int quota_fnum, SMB_NTQUOTA_STRUC
        unsigned int rparam_count=0, rdata_count=0;
        unsigned int sid_len;   
        memset(data,'\0',112);
-       
+
        if (!cli||!pqt) {
                smb_panic("cli_set_user_quota() called with NULL Pointer!");
        }
@@ -221,7 +221,7 @@ bool cli_set_user_quota(struct cli_state *cli, int quota_fnum, SMB_NTQUOTA_STRUC
        SBIG_UINT(data,24,pqt->softlim);
        SBIG_UINT(data,32,pqt->hardlim);
        sid_linearize(data+40, sid_len, &pqt->sid);
-       
+
        if (!cli_send_nt_trans(cli, 
                               NT_TRANSACT_SET_USER_QUOTA, 
                               0, 
@@ -278,7 +278,7 @@ bool cli_list_user_quota(struct cli_state *cli, int quota_fnum, SMB_NTQUOTA_LIST
        SIVAL(params, 4,0x00000000);
        SIVAL(params, 8,0x00000000);
        SIVAL(params,12,0x00000000);
-       
+
        if (!cli_send_nt_trans(cli, 
                               NT_TRANSACT_GET_USER_QUOTA, 
                               0, 
@@ -353,7 +353,7 @@ bool cli_list_user_quota(struct cli_state *cli, int quota_fnum, SMB_NTQUOTA_LIST
                        DEBUG(1,("Failed to send NT_TRANSACT_GET_USER_QUOTA\n"));
                        goto cleanup;
                }
-               
+
                SAFE_FREE(rparam);
                SAFE_FREE(rdata);
                if (!cli_receive_nt_trans(cli,
@@ -369,7 +369,7 @@ bool cli_list_user_quota(struct cli_state *cli, int quota_fnum, SMB_NTQUOTA_LIST
                } else {
                        ret = True;
                }
-       
+
                if (rdata_count == 0) {
                        break;  
                }
@@ -389,26 +389,26 @@ bool cli_list_user_quota(struct cli_state *cli, int quota_fnum, SMB_NTQUOTA_LIST
                                talloc_destroy(mem_ctx);
                                goto cleanup;
                        }
-       
+
                        if ((tmp_list_ent->quotas=TALLOC_ZERO_P(mem_ctx,SMB_NTQUOTA_STRUCT))==NULL) {
                                DEBUG(0,("TALLOC_ZERO() failed\n"));
                                talloc_destroy(mem_ctx);
                                goto cleanup;
                        }
-       
+
                        memcpy(tmp_list_ent->quotas,&qt,sizeof(qt));
                        tmp_list_ent->mem_ctx = mem_ctx;                
-       
+
                        DLIST_ADD((*pqt_list),tmp_list_ent);
                }
        }
 
+
        ret = True;
  cleanup:
        SAFE_FREE(rparam);
        SAFE_FREE(rdata);
+
        return ret;
 }
 
@@ -427,9 +427,9 @@ bool cli_get_fs_quota_info(struct cli_state *cli, int quota_fnum, SMB_NTQUOTA_ST
        }
 
        setup = TRANSACT2_QFSINFO;
-       
+
        SSVAL(param,0,SMB_FS_QUOTA_INFORMATION);
-       
+
        if (!cli_send_trans(cli, SMBtrans2, 
                    NULL, 
                    0, 0,
@@ -438,7 +438,7 @@ bool cli_get_fs_quota_info(struct cli_state *cli, int quota_fnum, SMB_NTQUOTA_ST
                    NULL, 0, 560)) {
                goto cleanup;
        }
-       
+
        if (!cli_receive_trans(cli, SMBtrans2,
                               &rparam, &rparam_count,
                               &rdata, &rdata_count)) {
@@ -455,7 +455,7 @@ bool cli_get_fs_quota_info(struct cli_state *cli, int quota_fnum, SMB_NTQUOTA_ST
        if (rdata_count < 48) {
                goto cleanup;
        }
-       
+
        /* unknown_1 24 NULL bytes in pdata*/
 
        /* the soft quotas 8 bytes (SMB_BIG_UINT)*/
@@ -541,7 +541,7 @@ bool cli_set_fs_quota_info(struct cli_state *cli, int quota_fnum, SMB_NTQUOTA_ST
                    data, 48, 0)) {
                goto cleanup;
        }
-       
+
        if (!cli_receive_trans(cli, SMBtrans2,
                               &rparam, &rparam_count,
                               &rdata, &rdata_count)) {
@@ -604,7 +604,7 @@ void dump_ntquota(SMB_NTQUOTA_STRUCT *qt, bool _verbose, bool _numeric, void (*_
                case SMB_USER_QUOTA_TYPE:
                        {
                                fstring username_str = {0};
-                               
+
                                if (_sidtostring) {
                                        _sidtostring(username_str,&qt->sid,_numeric);
                                } else {
index a543e073bc351f18722ca221178cb8dce3441845..08ab8cad145f2b8e7eac84143e43a55642ce72eb 100644 (file)
@@ -35,7 +35,7 @@ struct ip_service_name {
 static NTSTATUS make_dc_info_from_cldap_reply(TALLOC_CTX *mem_ctx,
                                              uint32_t flags,
                                              struct sockaddr_storage *ss,
-                                             struct netlogon_samlogon_response *r,
+                                             struct NETLOGON_SAM_LOGON_RESPONSE_EX *r,
                                              struct netr_DsRGetDCNameInfo **info);
 
 /****************************************************************
@@ -200,7 +200,7 @@ static NTSTATUS store_cldap_reply(TALLOC_CTX *mem_ctx,
 
        /* FIXME */
        r->sockaddr_size = 0x10; /* the w32 winsock addr size */
-       r->sockaddr.sa_family = 2; /* AF_INET */
+       r->sockaddr.sockaddr_family = 2; /* AF_INET */
        r->sockaddr.pdc_ip = talloc_strdup(mem_ctx, addr);
 
        ndr_err = ndr_push_struct_blob(&blob, mem_ctx, NULL, r,
@@ -228,6 +228,8 @@ static NTSTATUS store_cldap_reply(TALLOC_CTX *mem_ctx,
                }
        }
 
+       status = NT_STATUS_OK;
+
  done:
        data_blob_free(&blob);
 
@@ -272,12 +274,12 @@ static uint32_t get_cldap_reply_server_flags(struct netlogon_samlogon_response *
                case 3:
                case 18:
                case 19:
-                       return r->nt5.server_type;
+                       return r->data.nt5.server_type;
                case 4:
                case 5:
                case 6:
                case 7:
-                       return r->nt5_ex.server_type;
+                       return r->data.nt5_ex.server_type;
                case 8:
                case 9:
                case 10:
@@ -286,7 +288,7 @@ static uint32_t get_cldap_reply_server_flags(struct netlogon_samlogon_response *
                case 13:
                case 14:
                case 15:
-                       return r->nt5_ex.server_type;
+                       return r->data.nt5_ex.server_type;
                case 20:
                case 21:
                case 22:
@@ -296,11 +298,11 @@ static uint32_t get_cldap_reply_server_flags(struct netlogon_samlogon_response *
                case 26:
                case 27:
                case 28:
-                       return r->nt5_ex.server_type;
+                       return r->data.nt5_ex.server_type;
                case 29:
                case 30:
                case 31:
-                       return r->nt5_ex.server_type;
+                       return r->data.nt5_ex.server_type;
                default:
                        return 0;
        }
@@ -358,7 +360,6 @@ static NTSTATUS dsgetdcname_cache_fetch(TALLOC_CTX *mem_ctx,
        DATA_BLOB blob;
        enum ndr_err_code ndr_err;
        struct netr_DsRGetDCNameInfo *info;
-       struct netlogon_samlogon_response p;
        struct NETLOGON_SAM_LOGON_RESPONSE_EX r;
        NTSTATUS status;
 
@@ -389,10 +390,8 @@ static NTSTATUS dsgetdcname_cache_fetch(TALLOC_CTX *mem_ctx,
                return ndr_map_error2ntstatus(ndr_err);
        }
 
-       p.nt5_ex = r;
-
        status = make_dc_info_from_cldap_reply(mem_ctx, flags, NULL,
-                                              &p, &info);
+                                              &r, &info);
        if (!NT_STATUS_IS_OK(status)) {
                return status;
        }
@@ -787,7 +786,7 @@ static void map_dc_and_domain_names(uint32_t flags,
 static NTSTATUS make_dc_info_from_cldap_reply(TALLOC_CTX *mem_ctx,
                                              uint32_t flags,
                                              struct sockaddr_storage *ss,
-                                             struct netlogon_samlogon_response *r,
+                                             struct NETLOGON_SAM_LOGON_RESPONSE_EX *r,
                                              struct netr_DsRGetDCNameInfo **info)
 {
        const char *dc_hostname = NULL;
@@ -808,163 +807,28 @@ static NTSTATUS make_dc_info_from_cldap_reply(TALLOC_CTX *mem_ctx,
                dc_address_type = DS_ADDRESS_TYPE_INET;
        }
 
-       switch (r->ntver & 0x0000001f) {
-               case 0:
-               case 1:
-               case 16:
-               case 17:
-                       if (!ss) {
-                               dc_address      = r->nt4.server;
-                               dc_address_type = DS_ADDRESS_TYPE_NETBIOS;
-                       }
-
-                       map_dc_and_domain_names(flags,
-                                               r->nt4.server,
-                                               r->nt4.domain,
-                                               NULL,
-                                               NULL,
-                                               &dc_flags,
-                                               &dc_hostname,
-                                               &dc_domain_name);
-
-                       if (flags & DS_PDC_REQUIRED) {
-                               dc_flags = NBT_SERVER_WRITABLE | NBT_SERVER_PDC;
-                       }
-                       break;
-               case 2:
-               case 3:
-               case 18:
-               case 19:
-                       if (!ss) {
-                               dc_address      = r->nt5.pdc_ip;
-                               dc_address_type = DS_ADDRESS_TYPE_INET;
-                       }
-
-                       map_dc_and_domain_names(flags,
-                                               r->nt5.pdc_name,
-                                               r->nt5.domain_name,
-                                               r->nt5.pdc_dns_name,
-                                               r->nt5.dns_domain,
-                                               &dc_flags,
-                                               &dc_hostname,
-                                               &dc_domain_name);
-
-                       dc_flags        |= r->nt5.server_type;
-                       dc_forest       = r->nt5.forest;
-                       dc_domain_guid  = &r->nt5.domain_uuid;
-
-                       break;
-               case 4:
-               case 5:
-               case 6:
-               case 7:
-                       if (!ss) {
-                               dc_address      = r->nt5_ex.pdc_name;
-                               dc_address_type = DS_ADDRESS_TYPE_NETBIOS;
-                       }
-
-                       map_dc_and_domain_names(flags,
-                                               r->nt5_ex.pdc_name,
-                                               r->nt5_ex.domain,
-                                               r->nt5_ex.pdc_dns_name,
-                                               r->nt5_ex.dns_domain,
-                                               &dc_flags,
-                                               &dc_hostname,
-                                               &dc_domain_name);
-
-                       dc_flags        |= r->nt5_ex.server_type;
-                       dc_forest       = r->nt5_ex.forest;
-                       dc_domain_guid  = &r->nt5_ex.domain_uuid;
-                       dc_server_site  = r->nt5_ex.server_site;
-                       dc_client_site  = r->nt5_ex.client_site;
-
-                       break;
-               case 8:
-               case 9:
-               case 10:
-               case 11:
-               case 12:
-               case 13:
-               case 14:
-               case 15:
-                       if (!ss) {
-                               dc_address      = r->nt5_ex.sockaddr.pdc_ip;
-                               dc_address_type = DS_ADDRESS_TYPE_INET;
-                       }
-
-                       map_dc_and_domain_names(flags,
-                                               r->nt5_ex.pdc_name,
-                                               r->nt5_ex.domain,
-                                               r->nt5_ex.pdc_dns_name,
-                                               r->nt5_ex.dns_domain,
-                                               &dc_flags,
-                                               &dc_hostname,
-                                               &dc_domain_name);
-
-                       dc_flags        |= r->nt5_ex.server_type;
-                       dc_forest       = r->nt5_ex.forest;
-                       dc_domain_guid  = &r->nt5_ex.domain_uuid;
-                       dc_server_site  = r->nt5_ex.server_site;
-                       dc_client_site  = r->nt5_ex.client_site;
-
-                       break;
-               case 20:
-               case 21:
-               case 22:
-               case 23:
-               case 24:
-               case 25:
-               case 26:
-               case 27:
-               case 28:
-                       if (!ss) {
-                               dc_address      = r->nt5_ex.pdc_name;
-                               dc_address_type = DS_ADDRESS_TYPE_NETBIOS;
-                       }
+       if (!ss && r->sockaddr.pdc_ip) {
+               dc_address      = r->sockaddr.pdc_ip;
+               dc_address_type = DS_ADDRESS_TYPE_INET;
+       } else {
+               dc_address      = r->pdc_name;
+               dc_address_type = DS_ADDRESS_TYPE_NETBIOS;
+       }
 
-                       map_dc_and_domain_names(flags,
-                                               r->nt5_ex.pdc_name,
-                                               r->nt5_ex.domain,
-                                               r->nt5_ex.pdc_dns_name,
-                                               r->nt5_ex.dns_domain,
-                                               &dc_flags,
-                                               &dc_hostname,
-                                               &dc_domain_name);
-
-                       dc_flags        |= r->nt5_ex.server_type;
-                       dc_forest       = r->nt5_ex.forest;
-                       dc_domain_guid  = &r->nt5_ex.domain_uuid;
-                       dc_server_site  = r->nt5_ex.server_site;
-                       dc_client_site  = r->nt5_ex.client_site;
-
-                       break;
-               case 29:
-               case 30:
-               case 31:
-                       if (!ss) {
-                               dc_address      = r->nt5_ex.sockaddr.pdc_ip;
-                               dc_address_type = DS_ADDRESS_TYPE_INET;
-                       }
+       map_dc_and_domain_names(flags,
+                               r->pdc_name,
+                               r->domain,
+                               r->pdc_dns_name,
+                               r->dns_domain,
+                               &dc_flags,
+                               &dc_hostname,
+                               &dc_domain_name);
 
-                       map_dc_and_domain_names(flags,
-                                               r->nt5_ex.pdc_name,
-                                               r->nt5_ex.domain,
-                                               r->nt5_ex.pdc_dns_name,
-                                               r->nt5_ex.dns_domain,
-                                               &dc_flags,
-                                               &dc_hostname,
-                                               &dc_domain_name);
-
-                       dc_flags        |= r->nt5_ex.server_type;
-                       dc_forest       = r->nt5_ex.forest;
-                       dc_domain_guid  = &r->nt5_ex.domain_uuid;
-                       dc_server_site  = r->nt5_ex.server_site;
-                       dc_client_site  = r->nt5_ex.client_site;
-
-                       break;
-               default:
-                       return NT_STATUS_INVALID_PARAMETER;
-       }
+       dc_flags        |= r->server_type;
+       dc_forest       = r->forest;
+       dc_domain_guid  = &r->domain_uuid;
+       dc_server_site  = r->server_site;
+       dc_client_site  = r->client_site;
 
        return make_domain_controller_info(mem_ctx,
                                           dc_hostname,
@@ -1051,10 +915,10 @@ static NTSTATUS process_dc_dns(TALLOC_CTX *mem_ctx,
        }
 
        status = make_dc_info_from_cldap_reply(mem_ctx, flags, &dclist[i].ss,
-                                              r, info);
+                                              &r->data.nt5_ex, info);
        if (NT_STATUS_IS_OK(status)) {
                return store_cldap_reply(mem_ctx, flags, &dclist[i].ss,
-                                        nt_version, &r->nt5_ex);
+                                        nt_version, &r->data.nt5_ex);
        }
 
        return status;
@@ -1173,7 +1037,7 @@ static NTSTATUS process_dc_netbios(TALLOC_CTX *mem_ctx,
                        logon1.domain = talloc_strdup_upper(mem_ctx, domain_name);
                        NT_STATUS_HAVE_NO_MEMORY(logon1.domain);
 
-                       r->nt4 = logon1;
+                       r->data.nt4 = logon1;
                        r->ntver = nt_version;
 
                        namecache_store(tmp_dc_name, NBT_NAME_SERVER, 1, &ip_list);
@@ -1187,10 +1051,10 @@ static NTSTATUS process_dc_netbios(TALLOC_CTX *mem_ctx,
  make_reply:
 
        status = make_dc_info_from_cldap_reply(mem_ctx, flags, &dclist[i].ss,
-                                              r, info);
+                                              &r->data.nt5_ex, info);
        if (NT_STATUS_IS_OK(status) && store_cache) {
                return store_cldap_reply(mem_ctx, flags, &dclist[i].ss,
-                                        nt_version, &r->nt5_ex);
+                                        nt_version, &r->data.nt5_ex);
        }
 
        return status;
index f1b3d1415e94d090c6495ed5d3270534be641d5f..ea2c46953c7a612a9993a86f263063a660dd3242 100644 (file)
@@ -266,7 +266,7 @@ parse_ace(struct cli_state *ipc_cli,
         unsigned int aflags;
         unsigned int amask;
        DOM_SID sid;
-       SEC_ACCESS mask;
+       uint32_t mask;
        const struct perm_value *v;
         struct perm_value {
                 const char *perm;
index 7aa8c213e07faf8bd12756d69d5a8da34e1775b3..40a97d36745803e5bcbb1696736868da820f4a1e 100644 (file)
@@ -18,6 +18,7 @@ AC_PREFIX_DEFAULT(/usr/local/samba)
 rootsbindir="\${SBINDIR}"
 lockdir="\${VARDIR}/locks"
 piddir="\${VARDIR}/locks"
+ncalrpcdir="\${VARDIR}/ncalrpc"
 test "${mandir}" || mandir="\${prefix}/man"
 logfilebase="\${VARDIR}"
 privatedir="\${prefix}/private"
@@ -46,6 +47,7 @@ AC_ARG_WITH(fhs,
     codepagedir="\${MODULESDIR}"
     statedir="\${VARDIR}/lib/samba"
     cachedir="\${VARDIR}/lib/samba"
+    ncalrpcdir="\${VARDIR}/ncalrpc"
     AC_DEFINE(FHS_COMPATIBLE, 1, [Whether to use fully FHS-compatible paths])
     ;;
   esac])
@@ -114,6 +116,22 @@ AC_ARG_WITH(piddir,
     ;;
   esac])
 
+#################################################
+# set ncalrpc directory location
+AC_ARG_WITH(ncalprcdir,
+[AS_HELP_STRING([--with-ncalprcdir=DIR], [Where to put ncalrpc sockets ($ac_default_prefix/var/ncalrpc)])],
+[ case "$withval" in
+  yes|no)
+  #
+  # Just in case anybody calls it without argument
+  #
+    AC_MSG_WARN([--with-ncalrpcdir called without argument - will use default])
+  ;;
+  * )
+    ncalrpcdir="$withval"
+    ;;
+  esac])
+
 #################################################
 # set SWAT directory location
 AC_ARG_WITH(swatdir,
@@ -227,6 +245,7 @@ AC_ARG_WITH(mandir,
 AC_SUBST(configdir)
 AC_SUBST(lockdir)
 AC_SUBST(piddir)
+AC_SUBST(ncalrpcdir)
 AC_SUBST(logfilebase)
 AC_SUBST(ctdbdir)
 AC_SUBST(privatedir)
index 9e28db8b3967e951dddf936e9438d575fef0a7a4..f411176590113f9c368cdbfb3943fc48a9c1a240 100644 (file)
@@ -44,10 +44,6 @@ typedef struct _SMB_ACL4_INT_T
        SMB_ACE4_INT_T  *last;
 } SMB_ACL4_INT_T;
 
-extern int try_chown(connection_struct *conn, const char *fname, uid_t uid, gid_t gid);
-extern NTSTATUS unpack_nt_owners(int snum, uid_t *puser, gid_t *pgrp,
-       uint32 security_info_sent, SEC_DESC *psd);
-
 static SMB_ACL4_INT_T *get_validated_aclint(SMB4ACL_T *acl)
 {
        SMB_ACL4_INT_T *aclint = (SMB_ACL4_INT_T *)acl;
@@ -225,7 +221,7 @@ static bool smbacl4_nfs42win(TALLOC_CTX *mem_ctx, SMB4ACL_T *acl, /* in */
        }
 
        for (aceint=aclint->first; aceint!=NULL; aceint=(SMB_ACE4_INT_T *)aceint->next) {
-               SEC_ACCESS mask;
+               uint32_t mask;
                DOM_SID sid;
                SMB_ACE4PROP_T  *ace = &aceint->prop;
 
@@ -260,7 +256,7 @@ static bool smbacl4_nfs42win(TALLOC_CTX *mem_ctx, SMB4ACL_T *acl, /* in */
                DEBUG(10, ("mapped %d to %s\n", ace->who.id,
                           sid_string_dbg(&sid)));
 
-               init_sec_access(&mask, ace->aceMask);
+               mask = ace->aceMask;
                init_sec_ace(&nt_ace_list[good_aces++], &sid,
                        ace->aceType, mask,
                        ace->aceFlags & 0xf);
@@ -518,7 +514,7 @@ static bool smbacl4_fill_ace4(
        smbacl4_vfs_params *params,
        uid_t ownerUID,
        gid_t ownerGID,
-       SEC_ACE *ace_nt, /* input */
+       const SEC_ACE *ace_nt, /* input */
        SMB_ACE4PROP_T *ace_v4 /* output */
 )
 {
@@ -650,7 +646,7 @@ static int smbacl4_MergeIgnoreReject(
 
 static SMB4ACL_T *smbacl4_win2nfs4(
        const char *filename,
-       SEC_ACL *dacl,
+       const SEC_ACL *dacl,
        smbacl4_vfs_params *pparams,
        uid_t ownerUID,
        gid_t ownerGID
@@ -694,7 +690,7 @@ static SMB4ACL_T *smbacl4_win2nfs4(
 
 NTSTATUS smb_set_nt_acl_nfs4(files_struct *fsp,
        uint32 security_info_sent,
-       SEC_DESC *psd,
+       const SEC_DESC *psd,
        set_nfs4acl_native_fn_t set_nfs4_native)
 {
        smbacl4_vfs_params params;
index a2f3477b764b1927143272d3d7d10f580d4f01a4..241751c6a6f8a8d4f6bffdc9ccbb6c802708a958 100644 (file)
@@ -89,7 +89,7 @@ static NTSTATUS get_acl_blob(TALLOC_CTX *ctx,
        uint8_t *val = NULL;
        uint8_t *tmp;
        ssize_t sizeret;
-       int saved_errno;
+       int saved_errno = 0;
 
        ZERO_STRUCTP(pblob);
 
@@ -133,26 +133,6 @@ static NTSTATUS get_acl_blob(TALLOC_CTX *ctx,
        return NT_STATUS_OK;
 }
 
-static int mkdir_acl_xattr(vfs_handle_struct *handle,  const char *path, mode_t mode)
-{
-       return SMB_VFS_NEXT_MKDIR(handle, path, mode);
-}
-
-static int rmdir_acl_xattr(vfs_handle_struct *handle,  const char *path)
-{
-       return SMB_VFS_NEXT_RMDIR(handle, path);
-}
-
-static int open_acl_xattr(vfs_handle_struct *handle,  const char *fname, files_struct *fsp, int flags, mode_t mode)
-{
-       return SMB_VFS_NEXT_OPEN(handle, fname, fsp, flags, mode);
-}
-
-static int unlink_acl_xattr(vfs_handle_struct *handle,  const char *fname)
-{
-       return SMB_VFS_NEXT_UNLINK(handle, fname);
-}
-
 static NTSTATUS get_nt_acl_xattr_internal(vfs_handle_struct *handle,
                                        files_struct *fsp,
                                        const char *name,
@@ -198,6 +178,42 @@ static NTSTATUS get_nt_acl_xattr_internal(vfs_handle_struct *handle,
        return status;
 }
 
+static int mkdir_acl_xattr(vfs_handle_struct *handle,  const char *path, mode_t mode)
+{
+       return SMB_VFS_NEXT_MKDIR(handle, path, mode);
+}
+
+/*********************************************************************
+ * Currently this only works for existing files. Need to work on
+ * inheritance for new files.
+*********************************************************************/
+
+static int open_acl_xattr(vfs_handle_struct *handle,  const char *fname, files_struct *fsp, int flags, mode_t mode)
+{
+       uint32_t access_granted = 0;
+       SEC_DESC *pdesc = NULL;
+       NTSTATUS status = get_nt_acl_xattr_internal(handle,
+                                       NULL,
+                                       fname,
+                                       (OWNER_SECURITY_INFORMATION |
+                                        GROUP_SECURITY_INFORMATION |
+                                        DACL_SECURITY_INFORMATION),
+                                       &pdesc);
+        if (NT_STATUS_IS_OK(status)) {
+               /* See if we can access it. */
+               if (!se_access_check(pdesc,
+                                       handle->conn->server_info->ptok,
+                                       fsp->access_mask,
+                                       &access_granted,
+                                       &status)) {
+                       errno = map_errno_from_nt_status(status);
+                       return -1;
+               }
+        }
+
+       return SMB_VFS_NEXT_OPEN(handle, fname, fsp, flags, mode);
+}
+
 static NTSTATUS fget_nt_acl_xattr(vfs_handle_struct *handle, files_struct *fsp,
         uint32 security_info, SEC_DESC **ppdesc)
 {
@@ -222,7 +238,7 @@ static NTSTATUS get_nt_acl_xattr(vfs_handle_struct *handle,
                        security_info, ppdesc);
 }
 
-static NTSTATUS create_acl_blob(SEC_DESC *psd, DATA_BLOB *pblob)
+static NTSTATUS create_acl_blob(const SEC_DESC *psd, DATA_BLOB *pblob)
 {
        struct xattr_NTACL xacl;
        struct security_descriptor_timestamp sd_ts;
@@ -241,7 +257,7 @@ static NTSTATUS create_acl_blob(SEC_DESC *psd, DATA_BLOB *pblob)
 
        xacl.version = 2;
        xacl.info.sd_ts = &sd_ts;
-       xacl.info.sd_ts->sd = psd;
+       xacl.info.sd_ts->sd = CONST_DISCARD(SEC_DESC *, psd);
        unix_timespec_to_nt_time(&xacl.info.sd_ts->last_changed, curr);
 
        ndr_err = ndr_push_struct_blob(
@@ -261,7 +277,7 @@ static NTSTATUS store_acl_blob(files_struct *fsp,
                                DATA_BLOB *pblob)
 {
        int ret;
-       int saved_errno;
+       int saved_errno = 0;
 
        DEBUG(10,("store_acl_blob: storing blob length %u on file %s\n",
                        (unsigned int)pblob->length, fsp->fsp_name));
@@ -291,7 +307,7 @@ static NTSTATUS store_acl_blob(files_struct *fsp,
 }
 
 static NTSTATUS fset_nt_acl_xattr(vfs_handle_struct *handle, files_struct *fsp,
-        uint32 security_info_sent, SEC_DESC *psd)
+        uint32 security_info_sent, const SEC_DESC *psd)
 {
        NTSTATUS status;
        DATA_BLOB blob;
@@ -301,6 +317,22 @@ static NTSTATUS fset_nt_acl_xattr(vfs_handle_struct *handle, files_struct *fsp,
                return status;
        }
 
+       if ((security_info_sent & DACL_SECURITY_INFORMATION) &&
+                       psd->dacl != NULL &&
+                       (psd->type & (SE_DESC_DACL_AUTO_INHERITED|
+                               SE_DESC_DACL_AUTO_INHERIT_REQ))==
+                               (SE_DESC_DACL_AUTO_INHERITED|
+                               SE_DESC_DACL_AUTO_INHERIT_REQ) ) {
+               SEC_DESC *new_psd = NULL;
+               status = append_parent_acl(fsp, psd, &new_psd);
+               if (!NT_STATUS_IS_OK(status)) {
+                       /* Lower level acl set succeeded,
+                        * so still return OK. */
+                       return NT_STATUS_OK;
+               }
+               psd = new_psd;
+       }
+
        create_acl_blob(psd, &blob);
        store_acl_blob(fsp, &blob);
 
@@ -312,9 +344,7 @@ static NTSTATUS fset_nt_acl_xattr(vfs_handle_struct *handle, files_struct *fsp,
 static vfs_op_tuple skel_op_tuples[] =
 {
        {SMB_VFS_OP(mkdir_acl_xattr), SMB_VFS_OP_MKDIR, SMB_VFS_LAYER_TRANSPARENT},
-       {SMB_VFS_OP(rmdir_acl_xattr), SMB_VFS_OP_RMDIR, SMB_VFS_LAYER_TRANSPARENT},
        {SMB_VFS_OP(open_acl_xattr),  SMB_VFS_OP_OPEN,  SMB_VFS_LAYER_TRANSPARENT},
-       {SMB_VFS_OP(unlink_acl_xattr),SMB_VFS_OP_UNLINK,SMB_VFS_LAYER_TRANSPARENT},
 
         /* NT File ACL operations */
 
index 9409f3fa2039c18d7a5ae54c1357d99fa636e951..8c89d2fd9f935026d9175694701bb3557571e64f 100644 (file)
@@ -592,7 +592,6 @@ static size_t afs_to_nt_acl_common(struct afs_acl *afs_acl,
 {
        SEC_ACE *nt_ace_list;
        DOM_SID owner_sid, group_sid;
-       SEC_ACCESS mask;
        SEC_ACL *psa = NULL;
        int good_aces;
        size_t sd_size;
@@ -616,7 +615,7 @@ static size_t afs_to_nt_acl_common(struct afs_acl *afs_acl,
        good_aces = 0;
 
        while (afs_ace != NULL) {
-               uint32 nt_rights;
+               uint32_t nt_rights;
                uint8 flag = SEC_ACE_FLAG_OBJECT_INHERIT |
                        SEC_ACE_FLAG_CONTAINER_INHERIT;
 
@@ -633,9 +632,8 @@ static size_t afs_to_nt_acl_common(struct afs_acl *afs_acl,
                else
                        nt_rights = afs_to_nt_file_rights(afs_ace->rights);
 
-               init_sec_access(&mask, nt_rights);
                init_sec_ace(&nt_ace_list[good_aces++], &(afs_ace->sid),
-                            SEC_ACE_TYPE_ACCESS_ALLOWED, mask, flag);
+                            SEC_ACE_TYPE_ACCESS_ALLOWED, nt_rights, flag);
                afs_ace = afs_ace->next;
        }
 
@@ -717,12 +715,12 @@ static bool mappable_sid(const DOM_SID *sid)
 
 static bool nt_to_afs_acl(const char *filename,
                          uint32 security_info_sent,
-                         struct security_descriptor *psd,
+                         const struct security_descriptor *psd,
                          uint32 (*nt_to_afs_rights)(const char *filename,
                                                     const SEC_ACE *ace),
                          struct afs_acl *afs_acl)
 {
-       SEC_ACL *dacl;
+       const SEC_ACL *dacl;
        int i;
 
        /* Currently we *only* look at the dacl */
@@ -737,7 +735,7 @@ static bool nt_to_afs_acl(const char *filename,
        dacl = psd->dacl;
 
        for (i = 0; i < dacl->num_aces; i++) {
-               SEC_ACE *ace = &(dacl->aces[i]);
+               const SEC_ACE *ace = &(dacl->aces[i]);
                const char *dom_name, *name;
                enum lsa_SidType name_type;
                char *p;
@@ -887,7 +885,7 @@ static void merge_unknown_aces(struct afs_acl *src, struct afs_acl *dst)
 
 static NTSTATUS afs_set_nt_acl(vfs_handle_struct *handle, files_struct *fsp,
                           uint32 security_info_sent,
-                          struct security_descriptor *psd)
+                          const struct security_descriptor *psd)
 {
        struct afs_acl old_afs_acl, new_afs_acl;
        struct afs_acl dir_acl, file_acl;
@@ -1040,7 +1038,7 @@ static NTSTATUS afsacl_get_nt_acl(struct vfs_handle_struct *handle,
 NTSTATUS afsacl_fset_nt_acl(vfs_handle_struct *handle,
                         files_struct *fsp,
                         uint32 security_info_sent,
-                        SEC_DESC *psd)
+                        const SEC_DESC *psd)
 {
        return afs_set_nt_acl(handle, fsp, security_info_sent, psd);
 }
index 23c4d88134740bd42d071f85e3f7b69941f4f64a..a078b9f9f62c9801cb6a4a5059e4f8b004c9fdf4 100644 (file)
@@ -371,7 +371,7 @@ static bool aixjfs2_process_smbacl(files_struct *fsp, SMB4ACL_T *smbacl)
        return True;
 }
 
-static NTSTATUS aixjfs2_set_nt_acl_common(files_struct *fsp, uint32 security_info_sent, SEC_DESC *psd)
+static NTSTATUS aixjfs2_set_nt_acl_common(files_struct *fsp, uint32 security_info_sent, const SEC_DESC *psd)
 {
        acl_type_t      acl_type_info;
        NTSTATUS        result = NT_STATUS_ACCESS_DENIED;
@@ -395,7 +395,7 @@ static NTSTATUS aixjfs2_set_nt_acl_common(files_struct *fsp, uint32 security_inf
        return result;
 }
 
-NTSTATUS aixjfs2_fset_nt_acl(vfs_handle_struct *handle, files_struct *fsp, uint32 security_info_sent, SEC_DESC *psd)
+NTSTATUS aixjfs2_fset_nt_acl(vfs_handle_struct *handle, files_struct *fsp, uint32 security_info_sent, const SEC_DESC *psd)
 {
        return aixjfs2_set_nt_acl_common(fsp, security_info_sent, psd);
 }
index 381aa185610abd3fcd49f2da2265a7420ad30dea..372cdf2d5334923457bce21542ba97e1be6a84d1 100644 (file)
@@ -1036,7 +1036,7 @@ static NTSTATUS vfswrap_get_nt_acl(vfs_handle_struct *handle,
        return result;
 }
 
-static NTSTATUS vfswrap_fset_nt_acl(vfs_handle_struct *handle, files_struct *fsp, uint32 security_info_sent, SEC_DESC *psd)
+static NTSTATUS vfswrap_fset_nt_acl(vfs_handle_struct *handle, files_struct *fsp, uint32 security_info_sent, const SEC_DESC *psd)
 {
        NTSTATUS result;
 
index 1224ec3edb45355cb7e798740d6bfbc67658a608..9fadcd9e0cb994471fd5dd02f8520c6586defcd7 100644 (file)
@@ -202,7 +202,7 @@ static NTSTATUS smb_full_audit_get_nt_acl(vfs_handle_struct *handle,
                               SEC_DESC **ppdesc);
 static NTSTATUS smb_full_audit_fset_nt_acl(vfs_handle_struct *handle, files_struct *fsp,
                              uint32 security_info_sent,
-                             SEC_DESC *psd);
+                             const SEC_DESC *psd);
 static int smb_full_audit_chmod_acl(vfs_handle_struct *handle,
                           const char *path, mode_t mode);
 static int smb_full_audit_fchmod_acl(vfs_handle_struct *handle, files_struct *fsp,
@@ -1582,7 +1582,7 @@ static NTSTATUS smb_full_audit_get_nt_acl(vfs_handle_struct *handle,
 
 static NTSTATUS smb_full_audit_fset_nt_acl(vfs_handle_struct *handle, files_struct *fsp,
                              uint32 security_info_sent,
-                             SEC_DESC *psd)
+                             const SEC_DESC *psd)
 {
        NTSTATUS result;
 
index 39d2bb6c38c3e41c73daef549bc6659ecbde3390..fa0b4e97a5c1716a3f7635526b2897abb63072dc 100644 (file)
@@ -179,7 +179,7 @@ static int gpfs_get_nfs4_acl(const char *fname, SMB4ACL_T **ppacl)
                           "who: %d\n", gace->aceType, gace->aceIFlags,
                           gace->aceFlags, gace->aceMask, gace->aceWho));
 
-               memset(&smbace, 0, sizeof(SMB4ACE_T));
+               ZERO_STRUCT(smbace);
                if (gace->aceIFlags & ACE4_IFLAG_SPECIAL_ID) {
                        smbace.flags |= SMB_ACE4_ID_SPECIAL;
                        switch (gace->aceWho) {
@@ -365,7 +365,7 @@ static bool gpfsacl_process_smbacl(files_struct *fsp, SMB4ACL_T *smbacl)
        return True;
 }
 
-static NTSTATUS gpfsacl_set_nt_acl_internal(files_struct *fsp, uint32 security_info_sent, SEC_DESC *psd)
+static NTSTATUS gpfsacl_set_nt_acl_internal(files_struct *fsp, uint32 security_info_sent, const SEC_DESC *psd)
 {
        struct gpfs_acl *acl;
        NTSTATUS result = NT_STATUS_ACCESS_DENIED;
@@ -386,7 +386,7 @@ static NTSTATUS gpfsacl_set_nt_acl_internal(files_struct *fsp, uint32 security_i
        return result;
 }
 
-static NTSTATUS gpfsacl_fset_nt_acl(vfs_handle_struct *handle, files_struct *fsp, uint32 security_info_sent, SEC_DESC *psd)
+static NTSTATUS gpfsacl_fset_nt_acl(vfs_handle_struct *handle, files_struct *fsp, uint32 security_info_sent, const SEC_DESC *psd)
 {
        return gpfsacl_set_nt_acl_internal(fsp, security_info_sent, psd);
 }
@@ -739,7 +739,7 @@ static int gpfsacl_emu_chmod(const char *path, mode_t mode)
                if (haveAllowEntry[i]==True)
                        continue;
                
-               memset(&ace, 0, sizeof(SMB_ACE4PROP_T));
+               ZERO_STRUCT(ace);
                ace.aceType = SMB_ACE4_ACCESS_ALLOWED_ACE_TYPE;
                ace.flags |= SMB_ACE4_ID_SPECIAL;
                ace.who.special_id = i;
@@ -761,7 +761,7 @@ static int gpfsacl_emu_chmod(const char *path, mode_t mode)
        }
        
        /* don't add complementary DENY ACEs here */
-       memset(&fake_fsp, 0, sizeof(struct files_struct));
+       ZERO_STRUCT(fake_fsp);
        fake_fsp.fsp_name = (char *)path; /* no file_new is needed here */
        
        /* put the acl */
diff --git a/source3/modules/vfs_smb_traffic_analyzer.c b/source3/modules/vfs_smb_traffic_analyzer.c
new file mode 100644 (file)
index 0000000..9b4c1b3
--- /dev/null
@@ -0,0 +1,406 @@
+/*
+ * traffic-analyzer VFS module. Measure the smb traffic users create
+ * on the net.
+ *
+ * Copyright (C) Holger Hetterich, 2008
+ * Copyright (C) Jeremy Allison, 2008
+ *
+ * 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"
+
+/* abstraction for the send_over_network function */
+
+enum sock_type {INTERNET_SOCKET = 0, UNIX_DOMAIN_SOCKET};
+
+#define LOCAL_PATHNAME "/var/tmp/stadsocket"
+
+static int vfs_smb_traffic_analyzer_debug_level = DBGC_VFS;
+
+static enum sock_type smb_traffic_analyzer_connMode(vfs_handle_struct *handle)
+{
+       connection_struct *conn = handle->conn;
+        const char *Mode;
+        Mode=lp_parm_const_string(SNUM(conn), "smb_traffic_analyzer","mode", \
+                       "internet_socket");
+       if (strstr(Mode,"unix_domain_socket")) {
+               return UNIX_DOMAIN_SOCKET;
+       } else {
+               return INTERNET_SOCKET;
+       }
+}
+
+/* Connect to an internet socket */
+
+static int smb_traffic_analyzer_connect_inet_socket(vfs_handle_struct *handle,
+                                       const char *name, uint16_t port)
+{
+       /* Create a streaming Socket */
+       int sockfd = -1;
+       struct addrinfo hints;
+       struct addrinfo *ailist = NULL;
+       struct addrinfo *res = NULL;
+       int ret;
+
+       ZERO_STRUCT(hints);
+       /* By default make sure it supports TCP. */
+       hints.ai_socktype = SOCK_STREAM;
+       hints.ai_flags = AI_ADDRCONFIG;
+
+       ret = getaddrinfo(name,
+                       NULL,
+                       &hints,
+                       &ailist);
+
+        if (ret) {
+               DEBUG(3,("smb_traffic_analyzer_connect_inet_socket: "
+                       "getaddrinfo failed for name %s [%s]\n",
+                        name,
+                        gai_strerror(ret) ));
+               return -1;
+        }
+
+       DEBUG(3,("smb_traffic_analyzer: Internet socket mode. Hostname: %s,"
+               "Port: %i\n", name, port));
+
+       for (res = ailist; res; res = res->ai_next) {
+               struct sockaddr_storage ss;
+
+               if (!res->ai_addr || res->ai_addrlen == 0) {
+                       continue;
+               }
+
+               ZERO_STRUCT(ss);
+               memcpy(&ss, res->ai_addr, res->ai_addrlen);
+
+               sockfd = open_socket_out(SOCK_STREAM, &ss, port, 10000);
+               if (sockfd != -1) {
+                       break;
+               }
+       }
+
+       if (ailist) {
+               freeaddrinfo(ailist);
+       }
+
+        if (sockfd == -1) {
+               DEBUG(1, ("smb_traffic_analyzer: unable to create "
+                       "socket, error is %s",
+                       strerror(errno)));
+               return -1;
+       }
+
+       return sockfd;
+}
+
+/* Connect to a unix domain socket */
+
+static int smb_traffic_analyzer_connect_unix_socket(vfs_handle_struct *handle,
+                                               const char *name)
+{
+       /* Create the socket to stad */
+       int len, sock;
+       struct sockaddr_un remote;
+
+       DEBUG(7, ("smb_traffic_analyzer_connect_unix_socket: "
+                       "Unix domain socket mode. Using %s\n",
+                       name ));
+
+       if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
+               DEBUG(1, ("smb_traffic_analyzer_connect_unix_socket: "
+                       "Couldn't create socket, "
+                       "make sure stad is running!\n"));
+       }
+       remote.sun_family = AF_UNIX;
+       strlcpy(remote.sun_path, name,
+                   sizeof(remote.sun_path));
+       len=strlen(remote.sun_path) + sizeof(remote.sun_family);
+       if (connect(sock, (struct sockaddr *)&remote, len) == -1 ) {
+               DEBUG(1, ("smb_traffic_analyzer_connect_unix_socket: "
+                       "Could not connect to "
+                       "socket, make sure\nstad is running!\n"));
+               close(sock);
+               return -1;
+       }
+       return sock;
+}
+
+/* Private data allowing shared connection sockets. */
+
+struct refcounted_sock {
+       struct refcounted_sock *next, *prev;
+       char *name;
+       uint16_t port;
+       int sock;
+       unsigned int ref_count;
+};
+
+/* Send data over a socket */
+
+static void smb_traffic_analyzer_send_data(vfs_handle_struct *handle,
+                                       ssize_t result,
+                                       const char *file_name,
+                                       bool Write)
+{
+       struct refcounted_sock *rf_sock = NULL;
+       struct timeval tv;
+       time_t tv_sec;
+       struct tm *tm = NULL;
+       int seconds;
+       char *str = NULL;
+       size_t len;
+
+       SMB_VFS_HANDLE_GET_DATA(handle, rf_sock, struct refcounted_sock, return);
+
+       if (rf_sock == NULL || rf_sock->sock == -1) {
+               DEBUG(1, ("smb_traffic_analyzer_send_data: socket is "
+                       "closed\n"));
+               return;
+       }
+
+       GetTimeOfDay(&tv);
+       tv_sec = convert_timespec_to_time_t(convert_timeval_to_timespec(tv));
+       tm = localtime(&tv_sec);
+       if (!tm) {
+               return;
+       }
+       seconds=(float) (tv.tv_usec / 1000);
+
+       str = talloc_asprintf(talloc_tos(),
+                       "V1,%u,\"%s\",\"%s\",\"%c\",\"%s\",\"%s\","
+                       "\"%04d-%02d-%02d %02d:%02d:%02d.%03d\"\n",
+                       (unsigned int)result,
+                       handle->conn->server_info->sanitized_username,
+                       pdb_get_domain(handle->conn->server_info->sam_account),
+                       Write ? 'W' : 'R',
+                       handle->conn->connectpath,
+                       file_name,
+                       tm->tm_year+1900,
+                       tm->tm_mon+1,
+                       tm->tm_mday,
+                       tm->tm_hour,
+                       tm->tm_min,
+                       tm->tm_sec,
+                       (int)seconds);
+
+       if (!str) {
+               return;
+       }
+
+       len = strlen(str);
+
+       DEBUG(10, ("smb_traffic_analyzer_send_data_socket: sending %s\n",
+                       str));
+       if (write_data(rf_sock->sock, str, len) != len) {
+               DEBUG(1, ("smb_traffic_analyzer_send_data_socket: "
+                       "error sending data to socket!\n"));
+               return ;
+       }
+}
+
+static struct refcounted_sock *sock_list;
+
+static void smb_traffic_analyzer_free_data(void **pptr)
+{
+       struct refcounted_sock *rf_sock = *(struct refcounted_sock **)pptr;
+       if (rf_sock == NULL) {
+               return;
+       }
+       rf_sock->ref_count--;
+       if (rf_sock->ref_count != 0) {
+               return;
+       }
+       if (rf_sock->sock != -1) {
+               close(rf_sock->sock);
+       }
+       DLIST_REMOVE(sock_list, rf_sock);
+       TALLOC_FREE(rf_sock);
+}
+
+static int smb_traffic_analyzer_connect(struct vfs_handle_struct *handle,
+                         const char *service,
+                         const char *user)
+{
+       connection_struct *conn = handle->conn;
+       enum sock_type st = smb_traffic_analyzer_connMode(handle);
+       struct refcounted_sock *rf_sock = NULL;
+       const char *name = (st == UNIX_DOMAIN_SOCKET) ? LOCAL_PATHNAME :
+                               lp_parm_const_string(SNUM(conn),
+                                       "smb_traffic_analyzer",
+                               "host", "localhost");
+       uint16_t port = (st == UNIX_DOMAIN_SOCKET) ? 0 :
+                               atoi( lp_parm_const_string(SNUM(conn),
+                               "smb_traffic_analyzer", "port", "9430"));
+
+       /* Are we already connected ? */
+       for (rf_sock = sock_list; rf_sock; rf_sock = rf_sock->next) {
+               if (port == rf_sock->port &&
+                               (strcmp(name, rf_sock->name) == 0)) {
+                       break;
+               }
+       }
+
+       /* If we're connected already, just increase the
+        * reference count. */
+       if (rf_sock) {
+               rf_sock->ref_count++;
+       } else {
+               /* New connection. */
+               rf_sock = TALLOC_ZERO_P(NULL, struct refcounted_sock);
+               if (rf_sock == NULL) {
+                       errno = ENOMEM;
+                       return -1;
+               }
+               rf_sock->name = talloc_strdup(rf_sock, name);
+               if (rf_sock->name == NULL) {
+                       TALLOC_FREE(rf_sock);
+                       errno = ENOMEM;
+                       return -1;
+               }
+               rf_sock->port = port;
+               rf_sock->ref_count = 1;
+
+               if (st == UNIX_DOMAIN_SOCKET) {
+                       rf_sock->sock = smb_traffic_analyzer_connect_unix_socket(handle,
+                                                       name);
+               } else {
+
+                       rf_sock->sock = smb_traffic_analyzer_connect_inet_socket(handle,
+                                                       name,
+                                                       port);
+               }
+               if (rf_sock->sock == -1) {
+                       TALLOC_FREE(rf_sock);
+                       return -1;
+               }
+               DLIST_ADD(sock_list, rf_sock);
+       }
+
+       /* Store the private data. */
+       SMB_VFS_HANDLE_SET_DATA(handle, rf_sock, smb_traffic_analyzer_free_data,
+                               struct refcounted_sock, return -1);
+       return SMB_VFS_NEXT_CONNECT(handle, service, user);
+}
+
+/* VFS Functions: write, read, pread, pwrite for now */
+
+static ssize_t smb_traffic_analyzer_read(vfs_handle_struct *handle, \
+                               files_struct *fsp, void *data, size_t n)
+{
+       ssize_t result;
+
+       result = SMB_VFS_NEXT_READ(handle, fsp, data, n);
+       DEBUG(10, ("smb_traffic_analyzer_read: READ: %s\n", fsp->fsp_name ));
+
+       smb_traffic_analyzer_send_data(handle,
+                       result,
+                       fsp->fsp_name,
+                       false);
+       return result;
+}
+
+
+static ssize_t smb_traffic_analyzer_pread(vfs_handle_struct *handle, \
+               files_struct *fsp, void *data, size_t n, SMB_OFF_T offset)
+{
+       ssize_t result;
+
+       result = SMB_VFS_NEXT_PREAD(handle, fsp, data, n, offset);
+
+       DEBUG(10, ("smb_traffic_analyzer_pread: PREAD: %s\n", fsp->fsp_name ));
+
+       smb_traffic_analyzer_send_data(handle,
+                       result,
+                       fsp->fsp_name,
+                       false);
+
+       return result;
+}
+
+static ssize_t smb_traffic_analyzer_write(vfs_handle_struct *handle, \
+                       files_struct *fsp, const void *data, size_t n)
+{
+       ssize_t result;
+
+       result = SMB_VFS_NEXT_WRITE(handle, fsp, data, n);
+
+       DEBUG(10, ("smb_traffic_analyzer_write: WRITE: %s\n", fsp->fsp_name ));
+
+       smb_traffic_analyzer_send_data(handle,
+                       result,
+                       fsp->fsp_name,
+                       true);
+       return result;
+}
+
+static ssize_t smb_traffic_analyzer_pwrite(vfs_handle_struct *handle, \
+            files_struct *fsp, const void *data, size_t n, SMB_OFF_T offset)
+{
+       ssize_t result;
+
+       result = SMB_VFS_NEXT_PWRITE(handle, fsp, data, n, offset);
+
+       DEBUG(10, ("smb_traffic_analyzer_pwrite: PWRITE: %s\n", fsp->fsp_name ));
+
+       smb_traffic_analyzer_send_data(handle,
+                       result,
+                       fsp->fsp_name,
+                       true);
+       return result;
+}
+
+/* VFS operations we use */
+
+static vfs_op_tuple smb_traffic_analyzer_tuples[] = {
+
+        {SMB_VFS_OP(smb_traffic_analyzer_connect), SMB_VFS_OP_CONNECT,
+         SMB_VFS_LAYER_LOGGER},
+       {SMB_VFS_OP(smb_traffic_analyzer_read), SMB_VFS_OP_READ,
+        SMB_VFS_LAYER_LOGGER},
+       {SMB_VFS_OP(smb_traffic_analyzer_pread), SMB_VFS_OP_PREAD,
+        SMB_VFS_LAYER_LOGGER},
+       {SMB_VFS_OP(smb_traffic_analyzer_write), SMB_VFS_OP_WRITE,
+        SMB_VFS_LAYER_LOGGER},
+       {SMB_VFS_OP(smb_traffic_analyzer_pwrite), SMB_VFS_OP_PWRITE,
+        SMB_VFS_LAYER_LOGGER},
+               {SMB_VFS_OP(NULL),SMB_VFS_OP_NOOP,SMB_VFS_LAYER_NOOP}
+};
+
+/* Module initialization */
+
+NTSTATUS vfs_smb_traffic_analyzer_init(void)
+{
+       NTSTATUS ret = smb_register_vfs(SMB_VFS_INTERFACE_VERSION, \
+               "smb_traffic_analyzer", smb_traffic_analyzer_tuples);
+
+       if (!NT_STATUS_IS_OK(ret)) {
+               return ret;
+       }
+
+       vfs_smb_traffic_analyzer_debug_level =
+               debug_add_class("smb_traffic_analyzer");
+
+       if (vfs_smb_traffic_analyzer_debug_level == -1) {
+               vfs_smb_traffic_analyzer_debug_level = DBGC_VFS;
+               DEBUG(1, ("smb_traffic_analyzer_init: Couldn't register custom"
+                        "debugging class!\n"));
+       } else {
+               DEBUG(3, ("smb_traffic_analyzer_init: Debug class number of"
+                       "'smb_traffic_analyzer': %d\n", \
+                       vfs_smb_traffic_analyzer_debug_level));
+       }
+
+       return ret;
+}
index e933e473172da7c727e09907bd5c26cbc74e31be..3688b2386eb2fef8678cbe738324272002ee24c5 100644 (file)
@@ -166,7 +166,7 @@ static bool zfs_process_smbacl(files_struct *fsp, SMB4ACL_T *smbacl)
  */
 static NTSTATUS zfs_set_nt_acl(vfs_handle_struct *handle, files_struct *fsp,
                           uint32 security_info_sent,
-                          struct security_descriptor *psd)
+                          const struct security_descriptor *psd)
 {
        return smb_set_nt_acl_nfs4(fsp, security_info_sent, psd,
                        zfs_process_smbacl);
@@ -207,7 +207,7 @@ static NTSTATUS zfsacl_get_nt_acl(struct vfs_handle_struct *handle,
 static NTSTATUS zfsacl_fset_nt_acl(vfs_handle_struct *handle,
                         files_struct *fsp,
                         uint32 security_info_sent,
-                        SEC_DESC *psd)
+                        const SEC_DESC *psd)
 {
        return zfs_set_nt_acl(handle, fsp, security_info_sent, psd);
 }
index 474ae1ca1868946a706336d41f7113e6d398230f..814eaf7ca84984856a5ee53dd0998a63d7253d48 100644 (file)
@@ -178,7 +178,7 @@ logons are not enabled.\n", inet_ntoa(p->ip) ));
                                break;
                        }
 
-               case QUERYFORPDC:
+               case LOGON_PRIMARY_QUERY:
                        {
                                fstring mach_str, getdc_str;
                                fstring source_name;
@@ -253,7 +253,7 @@ logons are not enabled.\n", inet_ntoa(p->ip) ));
 
                                /* Construct reply. */
                                q = outbuf;
-                               SSVAL(q, 0, QUERYFORPDC_R);
+                               SSVAL(q, 0, NETLOGON_RESPONSE_FROM_PDC);
                                q += 2;
 
                                fstrcpy(reply_name,my_name);
@@ -292,7 +292,7 @@ logons are not enabled.\n", inet_ntoa(p->ip) ));
                                DEBUG(5,("process_logon_packet: GETDC request from %s at IP %s, \
 reporting %s domain %s 0x%x ntversion=%x lm_nt token=%x lm_20 token=%x\n",
                                        mach_str,inet_ntoa(p->ip), reply_name, lp_workgroup(),
-                                       QUERYFORPDC_R, (uint32)ntversion, (uint32)lmnttoken,
+                                       NETLOGON_RESPONSE_FROM_PDC, (uint32)ntversion, (uint32)lmnttoken,
                                        (uint32)lm20token ));
 
                                dump_data(4, (uint8 *)outbuf, PTR_DIFF(q, outbuf));
@@ -309,7 +309,7 @@ reporting %s domain %s 0x%x ntversion=%x lm_nt token=%x lm_20 token=%x\n",
                                return;
                        }
 
-               case SAMLOGON:
+               case LOGON_SAM_LOGON_REQUEST:
 
                        {
                                fstring getdc_str;
@@ -351,7 +351,7 @@ reporting %s domain %s 0x%x ntversion=%x lm_nt token=%x lm_20 token=%x\n",
                                domainsidsize = IVAL(q, 0);
                                q += 4;
 
-                               DEBUG(5,("process_logon_packet: SAMLOGON sidsize %d, len = %d\n", domainsidsize, len));
+                               DEBUG(5,("process_logon_packet: LOGON_SAM_LOGON_REQUEST sidsize %d, len = %d\n", domainsidsize, len));
 
                                if (domainsidsize < (len - PTR_DIFF(q, buf)) && (domainsidsize != 0)) {
                                        q += domainsidsize;
@@ -383,7 +383,7 @@ reporting %s domain %s 0x%x ntversion=%x lm_nt token=%x lm_20 token=%x\n",
                                lm20token = SVAL(q, 6);
                                q += 8;
 
-                               DEBUG(3,("process_logon_packet: SAMLOGON sidsize %d ntv %d\n", domainsidsize, ntversion));
+                               DEBUG(3,("process_logon_packet: LOGON_SAM_LOGON_REQUEST sidsize %d ntv %d\n", domainsidsize, ntversion));
 
                                /*
                                 * we respond regadless of whether the machine is in our password 
@@ -392,14 +392,14 @@ reporting %s domain %s 0x%x ntversion=%x lm_nt token=%x lm_20 token=%x\n",
                                 */
                                pull_ucs2_fstring(ascuser, uniuser);
                                pull_ucs2_fstring(asccomp, unicomp);
-                               DEBUG(5,("process_logon_packet: SAMLOGON user %s\n", ascuser));
+                               DEBUG(5,("process_logon_packet: LOGON_SAM_LOGON_REQUEST user %s\n", ascuser));
 
                                fstrcpy(reply_name, "\\\\"); /* Here it wants \\LOGONSERVER. */
                                fstrcat(reply_name, my_name);
 
-                               DEBUG(5,("process_logon_packet: SAMLOGON request from %s(%s) for %s, returning logon svr %s domain %s code %x token=%x\n",
+                               DEBUG(5,("process_logon_packet: LOGON_SAM_LOGON_REQUEST request from %s(%s) for %s, returning logon svr %s domain %s code %x token=%x\n",
                                        asccomp,inet_ntoa(p->ip), ascuser, reply_name, lp_workgroup(),
-                               SAMLOGON_R ,lmnttoken));
+                               LOGON_SAM_LOGON_RESPONSE ,lmnttoken));
 
                                /* Construct reply. */
 
@@ -408,9 +408,9 @@ reporting %s domain %s 0x%x ntversion=%x lm_nt token=%x lm_20 token=%x\n",
                                /* never, at least for now */
                                if ((ntversion < 11) || (SEC_ADS != lp_security()) || (ROLE_DOMAIN_PDC != lp_server_role())) {
                                        if (SVAL(uniuser, 0) == 0) {
-                                               SSVAL(q, 0, SAMLOGON_UNK_R);    /* user unknown */
+                                               SSVAL(q, 0, LOGON_SAM_LOGON_USER_UNKNOWN);      /* user unknown */
                                        } else {
-                                               SSVAL(q, 0, SAMLOGON_R);
+                                               SSVAL(q, 0, LOGON_SAM_LOGON_RESPONSE);
                                        }
 
                                        q += 2;
@@ -453,9 +453,9 @@ reporting %s domain %s 0x%x ntversion=%x lm_nt token=%x lm_20 token=%x\n",
                                                return;
                                        }
                                        if (SVAL(uniuser, 0) == 0) {
-                                               SIVAL(q, 0, SAMLOGON_AD_UNK_R); /* user unknown */
+                                               SIVAL(q, 0, LOGON_SAM_LOGON_USER_UNKNOWN_EX);   /* user unknown */
                                        } else {
-                                               SIVAL(q, 0, SAMLOGON_AD_R);
+                                               SIVAL(q, 0, LOGON_SAM_LOGON_RESPONSE_EX);
                                        }
                                        q += 4;
 
@@ -684,8 +684,8 @@ reporting %s domain %s 0x%x ntversion=%x lm_nt token=%x lm_20 token=%x\n",
                /* Announce change to UAS or SAM.  Send by the domain controller when a
                replication event is required. */
 
-               case SAM_UAS_CHANGE:
-                       DEBUG(5, ("Got SAM_UAS_CHANGE\n"));
+               case NETLOGON_ANNOUNCE_UAS:
+                       DEBUG(5, ("Got NETLOGON_ANNOUNCE_UAS\n"));
                        break;
 
                default:
diff --git a/source3/nsswitch/libwbclient/wbc_guid.c b/source3/nsswitch/libwbclient/wbc_guid.c
new file mode 100644 (file)
index 0000000..0cb33e9
--- /dev/null
@@ -0,0 +1,118 @@
+/*
+   Unix SMB/CIFS implementation.
+
+   Winbind client API
+
+   Copyright (C) Gerald (Jerry) Carter 2007
+
+
+   This library is free software; you can redistribute it and/or
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 3 of the License, or (at your option) any later version.
+
+   This library 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
+   Library General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/* Required Headers */
+
+#include "libwbclient.h"
+
+/** @brief Convert a binary GUID to a character string
+ *
+ * @param guid           Binary Guid
+ * @param **guid_string  Resulting character string
+ *
+ * @return #wbcErr
+ **/
+
+wbcErr wbcGuidToString(const struct wbcGuid *guid,
+                      char **guid_string)
+{
+       wbcErr wbc_status = WBC_ERR_UNKNOWN_FAILURE;
+
+       if (!guid) {
+               wbc_status = WBC_ERR_INVALID_PARAM;
+               BAIL_ON_WBC_ERROR(wbc_status);
+       }
+
+       *guid_string = talloc_asprintf(NULL,
+                                      "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
+                                      guid->time_low, guid->time_mid,
+                                      guid->time_hi_and_version,
+                                      guid->clock_seq[0],
+                                      guid->clock_seq[1],
+                                      guid->node[0], guid->node[1],
+                                      guid->node[2], guid->node[3],
+                                      guid->node[4], guid->node[5]);
+       BAIL_ON_PTR_ERROR((*guid_string), wbc_status);
+
+       wbc_status = WBC_ERR_SUCCESS;
+
+done:
+       return wbc_status;
+}
+
+/** @brief Convert a character string to a binary GUID
+ *
+ * @param *str          Character string
+ * @param guid          Resulting binary GUID
+ *
+ * @return #wbcErr
+ **/
+
+wbcErr wbcStringToGuid(const char *str,
+                      struct wbcGuid *guid)
+{
+       uint32_t time_low;
+       uint32_t time_mid, time_hi_and_version;
+       uint32_t clock_seq[2];
+       uint32_t node[6];
+       int i;
+       wbcErr wbc_status = WBC_ERR_UNKNOWN_FAILURE;
+
+       if (!guid) {
+               wbc_status = WBC_ERR_INVALID_PARAM;
+               BAIL_ON_WBC_ERROR(wbc_status);
+       }
+
+       if (!str) {
+               wbc_status = WBC_ERR_INVALID_PARAM;
+               BAIL_ON_WBC_ERROR(wbc_status);
+       }
+
+       if (11 == sscanf(str, "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
+                        &time_low, &time_mid, &time_hi_and_version,
+                        &clock_seq[0], &clock_seq[1],
+                        &node[0], &node[1], &node[2], &node[3], &node[4], &node[5])) {
+               wbc_status = WBC_ERR_SUCCESS;
+       } else if (11 == sscanf(str, "{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}",
+                               &time_low, &time_mid, &time_hi_and_version,
+                               &clock_seq[0], &clock_seq[1],
+                               &node[0], &node[1], &node[2], &node[3], &node[4], &node[5])) {
+               wbc_status = WBC_ERR_SUCCESS;
+       }
+
+       BAIL_ON_WBC_ERROR(wbc_status);
+
+       guid->time_low = time_low;
+       guid->time_mid = time_mid;
+       guid->time_hi_and_version = time_hi_and_version;
+       guid->clock_seq[0] = clock_seq[0];
+       guid->clock_seq[1] = clock_seq[1];
+
+       for (i=0;i<6;i++) {
+               guid->node[i] = node[i];
+       }
+
+       wbc_status = WBC_ERR_SUCCESS;
+
+done:
+       return wbc_status;
+}
index e32d66cd7136b329358769645c6820c80f129c31..1615fd33eef8e8da675b7b6aa9d88053570b45b6 100644 (file)
@@ -394,7 +394,7 @@ wbcErr wbcSetUidHwm(uid_t uid_hwm)
 
 /** @brief Set the highwater mark for allocated gids.
  *
- * @param uid_hwm      The new gid highwater mark value
+ * @param gid_hwm      The new gid highwater mark value
  *
  * @return #wbcErr
  **/
index 20b42b6efb3a7e75baa9350ee0db3659ee6153ae..713ba2e65b5baed7849a74f0a9fc1a76658acaef 100644 (file)
@@ -4,6 +4,7 @@
    Winbind client API
 
    Copyright (C) Gerald (Jerry) Carter 2007
+   Copyright (C) Guenther Deschner 2008
 
    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
@@ -260,6 +261,50 @@ done:
        return wbc_status;
 }
 
+static wbcErr wbc_create_logon_info(TALLOC_CTX *mem_ctx,
+                                   const struct winbindd_response *resp,
+                                   struct wbcLogonUserInfo **_i)
+{
+       wbcErr wbc_status = WBC_ERR_SUCCESS;
+       struct wbcLogonUserInfo *i;
+
+       i = talloc_zero(mem_ctx, struct wbcLogonUserInfo);
+       BAIL_ON_PTR_ERROR(i, wbc_status);
+
+       wbc_status = wbc_create_auth_info(i, resp, &i->info);
+       BAIL_ON_WBC_ERROR(wbc_status);
+
+       if (resp->data.auth.krb5ccname) {
+               wbc_status = wbcAddNamedBlob(&i->num_blobs,
+                                            &i->blobs,
+                                            "krb5ccname",
+                                            0,
+                                            (uint8_t *)resp->data.auth.krb5ccname,
+                                            strlen(resp->data.auth.krb5ccname)+1);
+               BAIL_ON_WBC_ERROR(wbc_status);
+       }
+
+       if (resp->data.auth.unix_username) {
+               wbc_status = wbcAddNamedBlob(&i->num_blobs,
+                                            &i->blobs,
+                                            "unix_username",
+                                            0,
+                                            (uint8_t *)resp->data.auth.unix_username,
+                                            strlen(resp->data.auth.unix_username)+1);
+               BAIL_ON_WBC_ERROR(wbc_status);
+       }
+
+       *_i = i;
+       i = NULL;
+done:
+       if (!WBC_ERROR_IS_OK(wbc_status) && i) {
+               wbcFreeMemory(i->blobs);
+       }
+
+       talloc_free(i);
+       return wbc_status;
+}
+
 /** @brief Authenticate with more detailed information
  *
  * @param params       Input parameters, WBC_AUTH_USER_LEVEL_HASH
@@ -331,6 +376,7 @@ wbcErr wbcAuthenticateUserEx(const struct wbcAuthUserParams *params,
                                params->account_name,
                                sizeof(request.data.auth.user)-1);
                }
+
                strncpy(request.data.auth.pass,
                        params->password.plaintext,
                        sizeof(request.data.auth.pass)-1);
@@ -416,6 +462,10 @@ wbcErr wbcAuthenticateUserEx(const struct wbcAuthUserParams *params,
                BAIL_ON_WBC_ERROR(wbc_status);
        }
 
+       if (params->flags) {
+               request.flags |= params->flags;
+       }
+
        wbc_status = wbcRequestResponse(cmd,
                                        &request,
                                        &response);
@@ -497,6 +547,101 @@ wbcErr wbcCheckTrustCredentials(const char *domain,
        return wbc_status;
 }
 
+/** @brief Trigger an extended logoff notification to Winbind for a specific user
+ *
+ * @param params      A wbcLogoffUserParams structure
+ * @param error       User output details on error
+ *
+ * @return #wbcErr
+ *
+ **/
+
+wbcErr wbcLogoffUserEx(const struct wbcLogoffUserParams *params,
+                      struct wbcAuthErrorInfo **error)
+{
+       struct winbindd_request request;
+       struct winbindd_response response;
+       wbcErr wbc_status = WBC_ERR_UNKNOWN_FAILURE;
+       int i;
+
+       /* validate input */
+
+       if (!params || !params->username) {
+               wbc_status = WBC_ERR_INVALID_PARAM;
+               BAIL_ON_WBC_ERROR(wbc_status);
+       }
+
+       if ((params->num_blobs > 0) && (params->blobs == NULL)) {
+               wbc_status = WBC_ERR_INVALID_PARAM;
+               BAIL_ON_WBC_ERROR(wbc_status);
+       }
+       if ((params->num_blobs == 0) && (params->blobs != NULL)) {
+               wbc_status = WBC_ERR_INVALID_PARAM;
+               BAIL_ON_WBC_ERROR(wbc_status);
+       }
+
+       ZERO_STRUCT(request);
+       ZERO_STRUCT(response);
+
+       strncpy(request.data.logoff.user, params->username,
+               sizeof(request.data.logoff.user)-1);
+
+       for (i=0; i<params->num_blobs; i++) {
+
+               if (strcasecmp(params->blobs[i].name, "ccfilename") == 0) {
+                       if (params->blobs[i].blob.data) {
+                               strncpy(request.data.logoff.krb5ccname,
+                                       (const char *)params->blobs[i].blob.data,
+                                       sizeof(request.data.logoff.krb5ccname) - 1);
+                       }
+                       continue;
+               }
+
+               if (strcasecmp(params->blobs[i].name, "user_uid") == 0) {
+                       if (params->blobs[i].blob.data) {
+                               memcpy(&request.data.logoff.uid,
+                                       params->blobs[i].blob.data,
+                                       MIN(params->blobs[i].blob.length,
+                                           sizeof(request.data.logoff.uid)));
+                       }
+                       continue;
+               }
+
+               if (strcasecmp(params->blobs[i].name, "flags") == 0) {
+                       if (params->blobs[i].blob.data) {
+                               memcpy(&request.flags,
+                                       params->blobs[i].blob.data,
+                                       MIN(params->blobs[i].blob.length,
+                                           sizeof(request.flags)));
+                       }
+                       continue;
+               }
+       }
+
+       /* Send request */
+
+       wbc_status = wbcRequestResponse(WINBINDD_PAM_LOGOFF,
+                                       &request,
+                                       &response);
+
+       /* Take the response above and return it to the caller */
+       if (response.data.auth.nt_status != 0) {
+               if (error) {
+                       wbc_status = wbc_create_error_info(NULL,
+                                                          &response,
+                                                          error);
+                       BAIL_ON_WBC_ERROR(wbc_status);
+               }
+
+               wbc_status = WBC_ERR_AUTH_ERROR;
+               BAIL_ON_WBC_ERROR(wbc_status);
+       }
+       BAIL_ON_WBC_ERROR(wbc_status);
+
+ done:
+       return wbc_status;
+}
+
 /** @brief Trigger a logoff notification to Winbind for a specific user
  *
  * @param username    Name of user to remove from Winbind's list of
@@ -794,3 +939,159 @@ wbcErr wbcChangeUserPassword(const char *username,
 done:
        return wbc_status;
 }
+
+/** @brief Logon a User
+ *
+ * @param[in]  params      Pointer to a wbcLogonUserParams structure
+ * @param[out] info        Pointer to a pointer to a wbcLogonUserInfo structure
+ * @param[out] error       Pointer to a pointer to a wbcAuthErrorInfo structure
+ * @param[out] policy      Pointer to a pointer to a wbcUserPasswordPolicyInfo structure
+ *
+ * @return #wbcErr
+ *
+ **/
+
+wbcErr wbcLogonUser(const struct wbcLogonUserParams *params,
+                   struct wbcLogonUserInfo **info,
+                   struct wbcAuthErrorInfo **error,
+                   struct wbcUserPasswordPolicyInfo **policy)
+{
+       wbcErr wbc_status = WBC_ERR_UNKNOWN_FAILURE;
+       int cmd = 0;
+       struct winbindd_request request;
+       struct winbindd_response response;
+       uint32_t i;
+
+       ZERO_STRUCT(request);
+       ZERO_STRUCT(response);
+
+       if (info) {
+               *info = NULL;
+       }
+       if (error) {
+               *error = NULL;
+       }
+       if (policy) {
+               *policy = NULL;
+       }
+
+       if (!params) {
+               wbc_status = WBC_ERR_INVALID_PARAM;
+               BAIL_ON_WBC_ERROR(wbc_status);
+       }
+
+       if (!params->username) {
+               wbc_status = WBC_ERR_INVALID_PARAM;
+               BAIL_ON_WBC_ERROR(wbc_status);
+       }
+
+       if ((params->num_blobs > 0) && (params->blobs == NULL)) {
+               wbc_status = WBC_ERR_INVALID_PARAM;
+               BAIL_ON_WBC_ERROR(wbc_status);
+       }
+       if ((params->num_blobs == 0) && (params->blobs != NULL)) {
+               wbc_status = WBC_ERR_INVALID_PARAM;
+               BAIL_ON_WBC_ERROR(wbc_status);
+       }
+
+       /* Initialize request */
+
+       cmd = WINBINDD_PAM_AUTH;
+       request.flags = WBFLAG_PAM_INFO3_TEXT |
+                       WBFLAG_PAM_USER_SESSION_KEY |
+                       WBFLAG_PAM_LMKEY;
+
+       if (!params->password) {
+               wbc_status = WBC_ERR_INVALID_PARAM;
+               BAIL_ON_WBC_ERROR(wbc_status);
+       }
+
+       strncpy(request.data.auth.user,
+               params->username,
+               sizeof(request.data.auth.user)-1);
+
+       strncpy(request.data.auth.pass,
+               params->password,
+               sizeof(request.data.auth.pass)-1);
+
+       for (i=0; i<params->num_blobs; i++) {
+
+               if (strcasecmp(params->blobs[i].name, "krb5_cc_type") == 0) {
+                       if (params->blobs[i].blob.data) {
+                               strncpy(request.data.auth.krb5_cc_type,
+                                       (const char *)params->blobs[i].blob.data,
+                                       sizeof(request.data.auth.krb5_cc_type) - 1);
+                       }
+                       continue;
+               }
+
+               if (strcasecmp(params->blobs[i].name, "user_uid") == 0) {
+                       if (params->blobs[i].blob.data) {
+                               memcpy(&request.data.auth.uid,
+                                       params->blobs[i].blob.data,
+                                       MIN(sizeof(request.data.auth.uid),
+                                           params->blobs[i].blob.length));
+                       }
+                       continue;
+               }
+
+               if (strcasecmp(params->blobs[i].name, "flags") == 0) {
+                       if (params->blobs[i].blob.data) {
+                               uint32_t flags;
+                               memcpy(&flags,
+                                       params->blobs[i].blob.data,
+                                       MIN(sizeof(flags),
+                                           params->blobs[i].blob.length));
+                               request.flags |= flags;
+                       }
+                       continue;
+               }
+
+               if (strcasecmp(params->blobs[i].name, "membership_of") == 0) {
+                       if (params->blobs[i].blob.data &&
+                           params->blobs[i].blob.data[0] > 0) {
+                               strncpy(request.data.auth.require_membership_of_sid,
+                                       (const char *)params->blobs[i].blob.data,
+                                       sizeof(request.data.auth.require_membership_of_sid) - 1);
+                       }
+                       continue;
+               }
+       }
+
+       wbc_status = wbcRequestResponse(cmd,
+                                       &request,
+                                       &response);
+
+       if (response.data.auth.nt_status != 0) {
+               if (error) {
+                       wbc_status = wbc_create_error_info(NULL,
+                                                          &response,
+                                                          error);
+                       BAIL_ON_WBC_ERROR(wbc_status);
+               }
+
+               wbc_status = WBC_ERR_AUTH_ERROR;
+               BAIL_ON_WBC_ERROR(wbc_status);
+       }
+       BAIL_ON_WBC_ERROR(wbc_status);
+
+       if (info) {
+               wbc_status = wbc_create_logon_info(NULL,
+                                                  &response,
+                                                  info);
+               BAIL_ON_WBC_ERROR(wbc_status);
+       }
+
+       if (policy) {
+               wbc_status = wbc_create_password_policy_info(NULL,
+                                                            &response,
+                                                            policy);
+               BAIL_ON_WBC_ERROR(wbc_status);
+       }
+
+done:
+       if (response.extra_data.data)
+               free(response.extra_data.data);
+
+       return wbc_status;
+}
index b5f167369cabfb8e11c97e0c12aff9b362f991a6..0d17b312ef42d4f4df54469dc9b9de15c9d99ff9 100644 (file)
@@ -380,7 +380,7 @@ wbcErr wbcGetgrent(struct group **grp)
  *
  * @param *account       The given user name
  * @param *num_groups    Number of elements returned in the groups array
- * @param **groups       Pointer to resulting gid_t array.
+ * @param **_groups      Pointer to resulting gid_t array.
  *
  * @return #wbcErr
  **/
index f4ffa4e5caac6a5bc250d44e486cf3bec3e8e24b..4cfdd792b5f5534ec112e5bb219018c885e3c30e 100644 (file)
@@ -223,9 +223,9 @@ wbcErr wbcLookupName(const char *domain,
 /** @brief Convert a SID to a domain and name
  *
  * @param *sid        Pointer to the domain SID to be resolved
- * @param domain      Resolved Domain name (possibly "")
- * @param name        Resolved User or group name
- * @param *name_type  Pointet to the resolved SID type
+ * @param pdomain     Resolved Domain name (possibly "")
+ * @param pname       Resolved User or group name
+ * @param *pname_type Pointet to the resolved SID type
  *
  * @return #wbcErr
  *
index 24568f910198430d54879f9754761da40f6331ab..b4868748aec9d108e1d1412e3ba4463052f0d5a4 100644 (file)
@@ -496,7 +496,7 @@ wbcErr wbcListTrusts(struct wbcDomainInfo **domains, size_t *num_domains)
 /** @brief Enumerate the domain trusts known by Winbind
  *
  * @param domain        Name of the domain to query for a DC
- * @flags               Bit flags used to control the domain location query
+ * @param flags         Bit flags used to control the domain location query
  * @param *dc_info      Pointer to the returned domain controller information
  *
  * @return #wbcErr
@@ -550,3 +550,187 @@ done:
 
        return wbc_status;
 }
+
+static wbcErr wbc_create_domain_controller_info_ex(TALLOC_CTX *mem_ctx,
+                                                  const struct winbindd_response *resp,
+                                                  struct wbcDomainControllerInfoEx **_i)
+{
+       wbcErr wbc_status = WBC_ERR_SUCCESS;
+       struct wbcDomainControllerInfoEx *i;
+       struct wbcGuid guid;
+
+       i = talloc(mem_ctx, struct wbcDomainControllerInfoEx);
+       BAIL_ON_PTR_ERROR(i, wbc_status);
+
+       i->dc_unc = talloc_strdup(i, resp->data.dsgetdcname.dc_unc);
+       BAIL_ON_PTR_ERROR(i->dc_unc, wbc_status);
+
+       i->dc_address = talloc_strdup(i, resp->data.dsgetdcname.dc_address);
+       BAIL_ON_PTR_ERROR(i->dc_address, wbc_status);
+
+       i->dc_address_type = resp->data.dsgetdcname.dc_address_type;
+
+       wbc_status = wbcStringToGuid(resp->data.dsgetdcname.domain_guid, &guid);
+       if (WBC_ERROR_IS_OK(wbc_status)) {
+               i->domain_guid = talloc(i, struct wbcGuid);
+               BAIL_ON_PTR_ERROR(i->domain_guid, wbc_status);
+
+               *i->domain_guid = guid;
+       } else {
+               i->domain_guid = NULL;
+       }
+
+       i->domain_name = talloc_strdup(i, resp->data.dsgetdcname.domain_name);
+       BAIL_ON_PTR_ERROR(i->domain_name, wbc_status);
+
+       if (resp->data.dsgetdcname.forest_name[0] != '\0') {
+               i->forest_name = talloc_strdup(i,
+                       resp->data.dsgetdcname.forest_name);
+               BAIL_ON_PTR_ERROR(i->forest_name, wbc_status);
+       } else {
+               i->forest_name = NULL;
+       }
+
+       i->dc_flags = resp->data.dsgetdcname.dc_flags;
+
+       if (resp->data.dsgetdcname.dc_site_name[0] != '\0') {
+               i->dc_site_name = talloc_strdup(i,
+                       resp->data.dsgetdcname.dc_site_name);
+               BAIL_ON_PTR_ERROR(i->dc_site_name, wbc_status);
+       } else {
+               i->dc_site_name = NULL;
+       }
+
+       if (resp->data.dsgetdcname.client_site_name[0] != '\0') {
+               i->client_site_name = talloc_strdup(i,
+                       resp->data.dsgetdcname.client_site_name);
+               BAIL_ON_PTR_ERROR(i->client_site_name, wbc_status);
+       } else {
+               i->client_site_name = NULL;
+       }
+
+       *_i = i;
+       i = NULL;
+
+done:
+       talloc_free(i);
+       return wbc_status;
+}
+
+/** @brief Get extended domain controller information
+ *
+ * @param domain        Name of the domain to query for a DC
+ * @param guid          Guid of the domain to query for a DC
+ * @param site          Site of the domain to query for a DC
+ * @param flags         Bit flags used to control the domain location query
+ * @param *dc_info      Pointer to the returned extended domain controller information
+ *
+ * @return #wbcErr
+ *
+ **/
+
+wbcErr wbcLookupDomainControllerEx(const char *domain,
+                                  struct wbcGuid *guid,
+                                  const char *site,
+                                  uint32_t flags,
+                                  struct wbcDomainControllerInfoEx **dc_info)
+{
+       wbcErr wbc_status = WBC_ERR_UNKNOWN_FAILURE;
+       struct winbindd_request request;
+       struct winbindd_response response;
+
+       /* validate input params */
+
+       if (!domain || !dc_info) {
+               wbc_status = WBC_ERR_INVALID_PARAM;
+               BAIL_ON_WBC_ERROR(wbc_status);
+       }
+
+       ZERO_STRUCT(request);
+       ZERO_STRUCT(response);
+
+       request.data.dsgetdcname.flags = flags;
+
+       strncpy(request.data.dsgetdcname.domain_name, domain,
+               sizeof(request.data.dsgetdcname.domain_name)-1);
+
+       if (site) {
+               strncpy(request.data.dsgetdcname.site_name, site,
+                       sizeof(request.data.dsgetdcname.site_name)-1);
+       }
+
+       if (guid) {
+               char *str = NULL;
+
+               wbc_status = wbcGuidToString(guid, &str);
+               BAIL_ON_WBC_ERROR(wbc_status);
+
+               strncpy(request.data.dsgetdcname.domain_guid, str,
+                       sizeof(request.data.dsgetdcname.domain_guid)-1);
+
+               wbcFreeMemory(str);
+       }
+
+       /* Send request */
+
+       wbc_status = wbcRequestResponse(WINBINDD_DSGETDCNAME,
+                                       &request,
+                                       &response);
+       BAIL_ON_WBC_ERROR(wbc_status);
+
+       if (dc_info) {
+               wbc_status = wbc_create_domain_controller_info_ex(NULL,
+                                                                 &response,
+                                                                 dc_info);
+               BAIL_ON_WBC_ERROR(wbc_status);
+       }
+
+       wbc_status = WBC_ERR_SUCCESS;
+done:
+       return wbc_status;
+}
+
+/** @brief Initialize a named blob and add to list of blobs
+ *
+ * @param[in,out] num_blobs     Pointer to the number of blobs
+ * @param[in,out] blobs         Pointer to an array of blobs
+ * @param[in]     name          Name of the new named blob
+ * @param[in]     flags         Flags of the new named blob
+ * @param[in]     data          Blob data of new blob
+ * @param[in]     length        Blob data length of new blob
+ *
+ * @return #wbcErr
+ *
+ **/
+
+wbcErr wbcAddNamedBlob(size_t *num_blobs,
+                      struct wbcNamedBlob **blobs,
+                      const char *name,
+                      uint32_t flags,
+                      uint8_t *data,
+                      size_t length)
+{
+       wbcErr wbc_status = WBC_ERR_UNKNOWN_FAILURE;
+       struct wbcNamedBlob blob;
+
+       *blobs = talloc_realloc(NULL, *blobs, struct wbcNamedBlob,
+                               *(num_blobs)+1);
+       BAIL_ON_PTR_ERROR(*blobs, wbc_status);
+
+       blob.name               = talloc_strdup(*blobs, name);
+       BAIL_ON_PTR_ERROR(blob.name, wbc_status);
+       blob.flags              = flags;
+       blob.blob.length        = length;
+       blob.blob.data          = (uint8_t *)talloc_memdup(*blobs, data, length);
+       BAIL_ON_PTR_ERROR(blob.blob.data, wbc_status);
+
+       (*(blobs))[*num_blobs] = blob;
+       *(num_blobs) += 1;
+
+       wbc_status = WBC_ERR_SUCCESS;
+done:
+       if (!WBC_ERROR_IS_OK(wbc_status) && blobs) {
+               wbcFreeMemory(*blobs);
+       }
+       return wbc_status;
+}
index cae3feec5bfa5eee2079cd2021df3b09cd18103e..00a3c98966cf5f92124475332f4a179959706dbb 100644 (file)
@@ -136,6 +136,19 @@ struct wbcSidWithAttr {
 #define WBC_SID_ATTR_GROUP_RESOURCE            0x20000000
 #define WBC_SID_ATTR_GROUP_LOGON_ID            0xC0000000
 
+/**
+ *  @brief Windows GUID
+ *
+ **/
+
+struct wbcGuid {
+       uint32_t time_low;
+       uint16_t time_mid;
+       uint16_t time_hi_and_version;
+       uint8_t clock_seq[2];
+       uint8_t node[6];
+};
+
 /**
  * @brief Domain Information
  **/
@@ -205,6 +218,36 @@ struct wbcAuthUserParams {
        } password;
 };
 
+/**
+ * @brief Generic Blob
+ **/
+
+struct wbcBlob {
+       uint8_t *data;
+       size_t length;
+};
+
+/**
+ * @brief Named Blob
+ **/
+
+struct wbcNamedBlob {
+       const char *name;
+       uint32_t flags;
+       struct wbcBlob blob;
+};
+
+/**
+ * @brief Logon User Parameters
+ **/
+
+struct wbcLogonUserParams {
+       const char *username;
+       const char *password;
+       size_t num_blobs;
+       struct wbcNamedBlob *blobs;
+};
+
 /**
  * @brief ChangePassword Parameters
  **/
@@ -297,6 +340,18 @@ struct wbcAuthUserInfo {
        struct wbcSidWithAttr *sids;
 };
 
+/**
+ * @brief Logon User Information
+ *
+ * Some of the strings are maybe NULL
+ **/
+
+struct wbcLogonUserInfo {
+       struct wbcAuthUserInfo *info;
+       size_t num_blobs;
+       struct wbcNamedBlob *blobs;
+};
+
 /* wbcAuthUserInfo->user_flags */
 
 #define WBC_AUTH_USER_INFO_GUEST                       0x00000001
@@ -372,6 +427,16 @@ enum wbcPasswordChangeRejectReason {
        WBC_PWD_CHANGE_REJECT_COMPLEXITY=5
 };
 
+/**
+ * @brief Logoff User Parameters
+ **/
+
+struct wbcLogoffUserParams {
+       const char *username;
+       size_t num_blobs;
+       struct wbcNamedBlob *blobs;
+};
+
 /*
  * DomainControllerInfo struct
  */
@@ -379,7 +444,20 @@ struct wbcDomainControllerInfo {
        char *dc_name;
 };
 
-
+/*
+ * DomainControllerInfoEx struct
+ */
+struct wbcDomainControllerInfoEx {
+       const char *dc_unc;
+       const char *dc_address;
+       uint16_t dc_address_type;
+       struct wbcGuid *domain_guid;
+       const char *domain_name;
+       const char *forest_name;
+       uint32_t dc_flags;
+       const char *dc_site_name;
+       const char *client_site_name;
+};
 
 /*
  * Memory Management
@@ -398,6 +476,16 @@ wbcErr wbcSidToString(const struct wbcDomainSid *sid,
 wbcErr wbcStringToSid(const char *sid_string,
                      struct wbcDomainSid *sid);
 
+/*
+ * Utility functions for dealing with GUIDs
+ */
+
+wbcErr wbcGuidToString(const struct wbcGuid *guid,
+                      char **guid_string);
+
+wbcErr wbcStringToGuid(const char *guid_string,
+                      struct wbcGuid *guid);
+
 wbcErr wbcPing(void);
 
 wbcErr wbcLibraryDetails(struct wbcLibraryDetails **details);
@@ -531,6 +619,12 @@ wbcErr wbcLookupDomainController(const char *domain,
                                 uint32_t flags,
                                 struct wbcDomainControllerInfo **dc_info);
 
+wbcErr wbcLookupDomainControllerEx(const char *domain,
+                                  struct wbcGuid *guid,
+                                  const char *site,
+                                  uint32_t flags,
+                                  struct wbcDomainControllerInfoEx **dc_info);
+
 /*
  * Athenticate functions
  */
@@ -542,10 +636,18 @@ wbcErr wbcAuthenticateUserEx(const struct wbcAuthUserParams *params,
                             struct wbcAuthUserInfo **info,
                             struct wbcAuthErrorInfo **error);
 
+wbcErr wbcLogonUser(const struct wbcLogonUserParams *params,
+                   struct wbcLogonUserInfo **info,
+                   struct wbcAuthErrorInfo **error,
+                   struct wbcUserPasswordPolicyInfo **policy);
+
 wbcErr wbcLogoffUser(const char *username,
                     uid_t uid,
                     const char *ccfilename);
 
+wbcErr wbcLogoffUserEx(const struct wbcLogoffUserParams *params,
+                      struct wbcAuthErrorInfo **error);
+
 wbcErr wbcChangeUserPassword(const char *username,
                             const char *old_password,
                             const char *new_password);
@@ -566,6 +668,14 @@ wbcErr wbcResolveWinsByIP(const char *ip, char **name);
  */
 wbcErr wbcCheckTrustCredentials(const char *domain,
                                struct wbcAuthErrorInfo **error);
-
+/*
+ * Helper functions
+ */
+wbcErr wbcAddNamedBlob(size_t *num_blobs,
+                      struct wbcNamedBlob **blobs,
+                      const char *name,
+                      uint32_t flags,
+                      uint8_t *data,
+                      size_t length);
 
 #endif      /* _WBCLIENT_H */
index beb0d47baaf344b530a3d00c20da7b32fdec6047..8d8868d0ef2d62b8a942a399c9a26adc97208f24 100644 (file)
 
 #include "pam_winbind.h"
 
+static int wbc_error_to_pam_error(wbcErr status)
+{
+       switch (status) {
+               case WBC_ERR_SUCCESS:
+                       return PAM_SUCCESS;
+               case WBC_ERR_NOT_IMPLEMENTED:
+                       return PAM_SERVICE_ERR;
+               case WBC_ERR_UNKNOWN_FAILURE:
+                       break;
+               case WBC_ERR_NO_MEMORY:
+                       return PAM_BUF_ERR;
+               case WBC_ERR_INVALID_SID:
+               case WBC_ERR_INVALID_PARAM:
+                       break;
+               case WBC_ERR_WINBIND_NOT_AVAILABLE:
+                       return PAM_AUTHINFO_UNAVAIL;
+               case WBC_ERR_DOMAIN_NOT_FOUND:
+                       return PAM_AUTHINFO_UNAVAIL;
+               case WBC_ERR_INVALID_RESPONSE:
+                       return PAM_BUF_ERR;
+               case WBC_ERR_NSS_ERROR:
+                       return PAM_USER_UNKNOWN;
+               case WBC_ERR_AUTH_ERROR:
+                       return PAM_AUTH_ERR;
+               case WBC_ERR_UNKNOWN_USER:
+                       return PAM_USER_UNKNOWN;
+               case WBC_ERR_UNKNOWN_GROUP:
+                       return PAM_USER_UNKNOWN;
+               case WBC_ERR_PWD_CHANGE_FAILED:
+                       break;
+       }
+
+       /* be paranoid */
+       return PAM_AUTH_ERR;
+}
+
 static const char *_pam_error_code_str(int err)
 {
        switch (err) {
@@ -401,6 +437,10 @@ static int _pam_parse(const pam_handle_t *pamh,
                ctrl |= WINBIND_WARN_PWD_EXPIRE;
        }
 
+       if (iniparser_getboolean(d, "global:mkhomedir", false)) {
+               ctrl |= WINBIND_MKHOMEDIR;
+       }
+
 config_from_pam:
        /* step through arguments */
        for (i=argc,v=argv; i-- > 0; ++v) {
@@ -433,6 +473,8 @@ config_from_pam:
                        ctrl |= WINBIND_KRB5_CCACHE_TYPE;
                else if (!strcasecmp(*v, "cached_login"))
                        ctrl |= WINBIND_CACHED_LOGIN;
+               else if (!strcasecmp(*v, "mkhomedir"))
+                       ctrl |= WINBIND_MKHOMEDIR;
                else {
                        __pam_log(pamh, ctrl, LOG_ERR,
                                 "pam_parse: unknown option: %s", *v);
@@ -452,13 +494,17 @@ config_from_pam:
        return ctrl;
 };
 
-static void _pam_winbind_free_context(struct pwb_context *ctx)
+static int _pam_winbind_free_context(struct pwb_context *ctx)
 {
+       if (!ctx) {
+               return 0;
+       }
+
        if (ctx->dict) {
                iniparser_freedict(ctx->dict);
        }
 
-       SAFE_FREE(ctx);
+       return 0;
 }
 
 static int _pam_winbind_init_context(pam_handle_t *pamh,
@@ -469,12 +515,12 @@ static int _pam_winbind_init_context(pam_handle_t *pamh,
 {
        struct pwb_context *r = NULL;
 
-       r = (struct pwb_context *)malloc(sizeof(struct pwb_context));
+       r = TALLOC_ZERO_P(NULL, struct pwb_context);
        if (!r) {
                return PAM_BUF_ERR;
        }
 
-       ZERO_STRUCTP(r);
+       talloc_set_destructor(r, _pam_winbind_free_context);
 
        r->pamh = pamh;
        r->flags = flags;
@@ -482,7 +528,7 @@ static int _pam_winbind_init_context(pam_handle_t *pamh,
        r->argv = argv;
        r->ctrl = _pam_parse(pamh, flags, argc, argv, &r->dict);
        if (r->ctrl == -1) {
-               _pam_winbind_free_context(r);
+               TALLOC_FREE(r);
                return PAM_SYSTEM_ERR;
        }
 
@@ -502,7 +548,7 @@ static void _pam_winbind_cleanup_func(pam_handle_t *pamh,
                               "(error_status = %d)", pamh, data,
                               error_status);
        }
-       SAFE_FREE(data);
+       TALLOC_FREE(data);
 }
 
 
@@ -644,80 +690,11 @@ static int _make_remark_format(struct pwb_context *ctx, int type, const char *fo
        return ret;
 }
 
-static int pam_winbind_request(struct pwb_context *ctx,
-                              enum winbindd_cmd req_type,
-                              struct winbindd_request *request,
-                              struct winbindd_response *response)
-{
-       /* Fill in request and send down pipe */
-       winbindd_init_request(request, req_type);
-
-       if (winbind_write_sock(request, sizeof(*request), 0, 0) == -1) {
-               _pam_log(ctx, LOG_ERR,
-                        "pam_winbind_request: write to socket failed!");
-               winbind_close_sock();
-               return PAM_SERVICE_ERR;
-       }
-
-       /* Wait for reply */
-       if (winbindd_read_reply(response) == -1) {
-               _pam_log(ctx, LOG_ERR,
-                        "pam_winbind_request: read from socket failed!");
-               winbind_close_sock();
-               return PAM_SERVICE_ERR;
-       }
-
-       /* We are done with the socket - close it and avoid mischeif */
-       winbind_close_sock();
-
-       /* Copy reply data from socket */
-       if (response->result == WINBINDD_OK) {
-               return PAM_SUCCESS;
-       }
-
-       /* no need to check for pam_error codes for getpwnam() */
-       switch (req_type) {
-
-               case WINBINDD_GETPWNAM:
-               case WINBINDD_LOOKUPNAME:
-                       if (strlen(response->data.auth.nt_status_string) > 0) {
-                               _pam_log(ctx, LOG_ERR,
-                                        "request failed, NT error was %s",
-                                        response->data.auth.nt_status_string);
-                       } else {
-                               _pam_log(ctx, LOG_ERR, "request failed");
-                       }
-                       return PAM_USER_UNKNOWN;
-               default:
-                       break;
-       }
-
-       if (response->data.auth.pam_error != PAM_SUCCESS) {
-               _pam_log(ctx, LOG_ERR,
-                        "request failed: %s, "
-                        "PAM error was %s (%d), NT error was %s",
-                        response->data.auth.error_string,
-                        pam_strerror(ctx->pamh, response->data.auth.pam_error),
-                        response->data.auth.pam_error,
-                        response->data.auth.nt_status_string);
-               return response->data.auth.pam_error;
-       }
-
-       _pam_log(ctx, LOG_ERR, "request failed, but PAM error 0!");
-
-       return PAM_SERVICE_ERR;
-}
-
 static int pam_winbind_request_log(struct pwb_context *ctx,
-                                  enum winbindd_cmd req_type,
-                                  struct winbindd_request *request,
-                                  struct winbindd_response *response,
-                                  const char *user)
+                                  int retval,
+                                  const char *user,
+                                  const char *fn)
 {
-       int retval;
-
-       retval = pam_winbind_request(ctx, req_type, request, response);
-
        switch (retval) {
        case PAM_AUTH_ERR:
                /* incorrect password */
@@ -749,33 +726,65 @@ static int pam_winbind_request_log(struct pwb_context *ctx,
                return retval;
        case PAM_SUCCESS:
                /* Otherwise, the authentication looked good */
-               switch (req_type) {
-                       case WINBINDD_INFO:
-                               break;
-                       case WINBINDD_PAM_AUTH:
-                               _pam_log(ctx, LOG_NOTICE,
-                                        "user '%s' granted access", user);
-                               break;
-                       case WINBINDD_PAM_CHAUTHTOK:
-                               _pam_log(ctx, LOG_NOTICE,
-                                        "user '%s' password changed", user);
-                               break;
-                       default:
-                               _pam_log(ctx, LOG_NOTICE,
-                                        "user '%s' OK", user);
-                               break;
+               if (strcmp(fn, "wbcLogonUser") == 0) {
+                       _pam_log(ctx, LOG_NOTICE,
+                                "user '%s' granted access", user);
+               } else {
+                       _pam_log(ctx, LOG_NOTICE,
+                                "user '%s' OK", user);
                }
-
                return retval;
        default:
                /* we don't know anything about this return value */
                _pam_log(ctx, LOG_ERR,
-                        "internal module error (retval = %d, user = '%s')",
-                        retval, user);
+                        "internal module error (retval = %s(%d), user = '%s')",
+                       _pam_error_code_str(retval), retval, user);
                return retval;
        }
 }
 
+static int wbc_auth_error_to_pam_error(struct pwb_context *ctx,
+                                      struct wbcAuthErrorInfo *e,
+                                      wbcErr status,
+                                      const char *username,
+                                      const char *fn)
+{
+       int ret = PAM_AUTH_ERR;
+
+       if (WBC_ERROR_IS_OK(status)) {
+               _pam_log_debug(ctx, LOG_DEBUG, "request %s succeeded",
+                       fn);
+               ret = PAM_SUCCESS;
+               return pam_winbind_request_log(ctx, ret, username, fn);
+       }
+
+       if (e) {
+               if (e->pam_error != PAM_SUCCESS) {
+                       _pam_log(ctx, LOG_ERR,
+                                "request %s failed: %s, "
+                                "PAM error: %s (%d), NTSTATUS: %s, "
+                                "Error message was: %s",
+                                fn,
+                                wbcErrorString(status),
+                                _pam_error_code_str(e->pam_error),
+                                e->pam_error,
+                                e->nt_string,
+                                e->display_string);
+                       ret = e->pam_error;
+                       return pam_winbind_request_log(ctx, ret, username, fn);
+               }
+
+               _pam_log(ctx, LOG_ERR, "request %s failed, but PAM error 0!", fn);
+
+               ret = PAM_SERVICE_ERR;
+               return pam_winbind_request_log(ctx, ret, username, fn);
+       }
+
+       ret = wbc_error_to_pam_error(status);
+       return pam_winbind_request_log(ctx, ret, username, fn);
+}
+
+
 /**
  * send a password expiry message if required
  *
@@ -848,29 +857,34 @@ static bool _pam_send_password_expiry_message(struct pwb_context *ctx,
  */
 
 static void _pam_warn_password_expiry(struct pwb_context *ctx,
-                                     const struct winbindd_response *response,
+                                     const struct wbcAuthUserInfo *info,
+                                     const struct wbcUserPasswordPolicyInfo *policy,
                                      int warn_pwd_expire,
                                      bool *already_expired)
 {
        time_t now = time(NULL);
        time_t next_change = 0;
 
+       if (!info || !policy) {
+               return;
+       }
+
        if (already_expired) {
                *already_expired = false;
        }
 
-       /* accounts with ACB_PWNOEXP set never receive a warning */
-       if (response->data.auth.info3.acct_flags & ACB_PWNOEXP) {
+       /* accounts with WBC_ACB_PWNOEXP set never receive a warning */
+       if (info->acct_flags & WBC_ACB_PWNOEXP) {
                return;
        }
 
        /* no point in sending a warning if this is a grace logon */
-       if (PAM_WB_GRACE_LOGON(response->data.auth.info3.user_flgs)) {
+       if (PAM_WB_GRACE_LOGON(info->user_flags)) {
                return;
        }
 
        /* check if the info3 must change timestamp has been set */
-       next_change = response->data.auth.info3.pass_must_change_time;
+       next_change = info->pass_must_change_time;
 
        if (_pam_send_password_expiry_message(ctx, next_change, now,
                                              warn_pwd_expire,
@@ -881,12 +895,11 @@ static void _pam_warn_password_expiry(struct pwb_context *ctx,
        /* now check for the global password policy */
        /* good catch from Ralf Haferkamp: an expiry of "never" is translated
         * to -1 */
-       if (response->data.auth.policy.expire <= 0) {
+       if (policy->expire <= 0) {
                return;
        }
 
-       next_change = response->data.auth.info3.pass_last_set_time +
-                     response->data.auth.policy.expire;
+       next_change = info->pass_last_set_time + policy->expire;
 
        if (_pam_send_password_expiry_message(ctx, next_change, now,
                                              warn_pwd_expire,
@@ -944,33 +957,33 @@ static bool winbind_name_to_sid_string(struct pwb_context *ctx,
                                       int sid_list_buffer_size)
 {
        const char* sid_string;
-       struct winbindd_response sid_response;
 
        /* lookup name? */
        if (IS_SID_STRING(name)) {
                sid_string = name;
        } else {
-               struct winbindd_request sid_request;
-
-               ZERO_STRUCT(sid_request);
-               ZERO_STRUCT(sid_response);
+               wbcErr wbc_status;
+               struct wbcDomainSid sid;
+               enum wbcSidType type;
+               char *sid_str;
 
                _pam_log_debug(ctx, LOG_DEBUG,
                               "no sid given, looking up: %s\n", name);
 
-               /* fortunatly winbindd can handle non-separated names */
-               strncpy(sid_request.data.name.name, name,
-                       sizeof(sid_request.data.name.name) - 1);
-
-               if (pam_winbind_request_log(ctx, WINBINDD_LOOKUPNAME,
-                                           &sid_request, &sid_response,
-                                           user)) {
+               wbc_status = wbcLookupName("", name, &sid, &type);
+               if (!WBC_ERROR_IS_OK(wbc_status)) {
                        _pam_log(ctx, LOG_INFO,
                                 "could not lookup name: %s\n", name);
                        return false;
                }
 
-               sid_string = sid_response.data.sid.sid;
+               wbc_status = wbcSidToString(&sid, &sid_str);
+               if (!WBC_ERROR_IS_OK(wbc_status)) {
+                       return false;
+               }
+
+               wbcFreeMemory(sid_str);
+               sid_string = sid_str;
        }
 
        if (!safe_append_string(sid_list_buffer, sid_string,
@@ -1055,15 +1068,28 @@ out:
  */
 
 static void _pam_setup_krb5_env(struct pwb_context *ctx,
-                               const char *krb5ccname)
+                               struct wbcLogonUserInfo *info)
 {
        char var[PATH_MAX];
        int ret;
+       uint32_t i;
+       const char *krb5ccname = NULL;
 
        if (off(ctx->ctrl, WINBIND_KRB5_AUTH)) {
                return;
        }
 
+       if (!info) {
+               return;
+       }
+
+       for (i=0; i < info->num_blobs; i++) {
+               if (strcasecmp(info->blobs[i].name, "krb5ccname") == 0) {
+                       krb5ccname = (const char *)info->blobs[i].blob.data;
+                       break;
+               }
+       }
+
        if (!krb5ccname || (strlen(krb5ccname) == 0)) {
                return;
        }
@@ -1083,6 +1109,41 @@ static void _pam_setup_krb5_env(struct pwb_context *ctx,
        }
 }
 
+/**
+ * Copy unix username if available (further processed in PAM).
+ *
+ * @param ctx PAM winbind context
+ * @param user_ret A pointer that holds a pointer to a string
+ * @param unix_username A username
+ *
+ * @return void.
+ */
+
+static void _pam_setup_unix_username(struct pwb_context *ctx,
+                                    char **user_ret,
+                                    struct wbcLogonUserInfo *info)
+{
+       const char *unix_username = NULL;
+       uint32_t i;
+
+       if (!user_ret || !info) {
+               return;
+       }
+
+       for (i=0; i < info->num_blobs; i++) {
+               if (strcasecmp(info->blobs[i].name, "unix_username") == 0) {
+                       unix_username = (const char *)info->blobs[i].blob.data;
+                       break;
+               }
+       }
+
+       if (!unix_username || !unix_username[0]) {
+               return;
+       }
+
+       *user_ret = strdup(unix_username);
+}
+
 /**
  * Set string into the PAM stack.
  *
@@ -1104,14 +1165,13 @@ static void _pam_set_data_string(struct pwb_context *ctx,
                return;
        }
 
-       ret = pam_set_data(ctx->pamh, data_name, (void *)strdup(value),
+       ret = pam_set_data(ctx->pamh, data_name, talloc_strdup(NULL, value),
                           _pam_winbind_cleanup_func);
        if (ret) {
                _pam_log_debug(ctx, LOG_DEBUG,
                               "Could not set data %s: %s\n",
                               data_name, pam_strerror(ctx->pamh, ret));
        }
-
 }
 
 /**
@@ -1125,16 +1185,16 @@ static void _pam_set_data_string(struct pwb_context *ctx,
  */
 
 static void _pam_set_data_info3(struct pwb_context *ctx,
-                               struct winbindd_response *response)
+                               const struct wbcAuthUserInfo *info)
 {
        _pam_set_data_string(ctx, PAM_WINBIND_HOMEDIR,
-                            response->data.auth.info3.home_dir);
+                            info->home_directory);
        _pam_set_data_string(ctx, PAM_WINBIND_LOGONSCRIPT,
-                            response->data.auth.info3.logon_script);
+                            info->logon_script);
        _pam_set_data_string(ctx, PAM_WINBIND_LOGONSERVER,
-                            response->data.auth.info3.logon_srv);
+                            info->logon_server);
        _pam_set_data_string(ctx, PAM_WINBIND_PROFILEPATH,
-                            response->data.auth.info3.profile_path);
+                            info->profile_path);
 }
 
 /**
@@ -1216,80 +1276,235 @@ static void _pam_warn_krb5_failure(struct pwb_context *ctx,
        }
 }
 
+static bool _pam_check_remark_auth_err(struct pwb_context *ctx,
+                                      const struct wbcAuthErrorInfo *e,
+                                      const char *nt_status_string,
+                                      int *pam_error)
+{
+       const char *ntstatus = NULL;
+       const char *error_string = NULL;
+
+       if (!e || !pam_error) {
+               return false;
+       }
+
+       ntstatus = e->nt_string;
+       if (!ntstatus) {
+               return false;
+       }
+
+       if (strcasecmp(ntstatus, nt_status_string) == 0) {
+
+               error_string = _get_ntstatus_error_string(nt_status_string);
+               if (error_string) {
+                       _make_remark(ctx, PAM_ERROR_MSG, error_string);
+                       *pam_error = e->pam_error;
+                       return true;
+               }
+
+               if (e->display_string) {
+                       _make_remark(ctx, PAM_ERROR_MSG, e->display_string);
+                       *pam_error = e->pam_error;
+                       return true;
+               }
+
+               _make_remark(ctx, PAM_ERROR_MSG, nt_status_string);
+               *pam_error = e->pam_error;
+
+               return true;
+       }
+
+       return false;
+};
+
 /**
  * Compose Password Restriction String for a PAM_ERROR_MSG conversation.
  *
- * @param response The struct winbindd_response.
+ * @param i The wbcUserPasswordPolicyInfo struct.
  *
- * @return string (caller needs to free).
+ * @return string (caller needs to talloc_free).
  */
 
-static char *_pam_compose_pwd_restriction_string(struct winbindd_response *response)
+static char *_pam_compose_pwd_restriction_string(struct pwb_context *ctx,
+                                                struct wbcUserPasswordPolicyInfo *i)
 {
        char *str = NULL;
-       size_t offset = 0, ret = 0, str_size = 1024;
 
-       str = (char *)malloc(str_size);
-       if (!str) {
-               return NULL;
+       if (!i) {
+               goto failed;
        }
 
-       memset(str, '\0', str_size);
-
-       offset = snprintf(str, str_size, "Your password ");
-       if (offset == -1) {
+       str = talloc_asprintf(ctx, "Your password ");
+       if (!str) {
                goto failed;
        }
 
-       if (response->data.auth.policy.min_length_password > 0) {
-               ret = snprintf(str+offset, str_size-offset,
+       if (i->min_length_password > 0) {
+               str = talloc_asprintf_append(str,
                               "must be at least %d characters; ",
-                              response->data.auth.policy.min_length_password);
-               if (ret == -1) {
+                              i->min_length_password);
+               if (!str) {
                        goto failed;
                }
-               offset += ret;
        }
 
-       if (response->data.auth.policy.password_history > 0) {
-               ret = snprintf(str+offset, str_size-offset,
+       if (i->password_history > 0) {
+               str = talloc_asprintf_append(str,
                               "cannot repeat any of your previous %d "
                               "passwords; ",
-                              response->data.auth.policy.password_history);
-               if (ret == -1) {
+                              i->password_history);
+               if (!str) {
                        goto failed;
                }
-               offset += ret;
        }
 
-       if (response->data.auth.policy.password_properties &
-           DOMAIN_PASSWORD_COMPLEX) {
-               ret = snprintf(str+offset, str_size-offset,
+       if (i->password_properties & WBC_DOMAIN_PASSWORD_COMPLEX) {
+               str = talloc_asprintf_append(str,
                               "must contain capitals, numerals "
                               "or punctuation; "
                               "and cannot contain your account "
                               "or full name; ");
-               if (ret == -1) {
+               if (!str) {
                        goto failed;
                }
-               offset += ret;
        }
 
-       ret = snprintf(str+offset, str_size-offset,
+       str = talloc_asprintf_append(str,
                       "Please type a different password. "
                       "Type a password which meets these requirements in "
                       "both text boxes.");
-       if (ret == -1) {
+       if (!str) {
                goto failed;
        }
 
        return str;
 
  failed:
-       SAFE_FREE(str);
+       TALLOC_FREE(str);
        return NULL;
 }
 
+static int _pam_create_homedir(struct pwb_context *ctx,
+                              const char *dirname,
+                              mode_t mode)
+{
+       struct stat sbuf;
+
+       if (stat(dirname, &sbuf) == 0) {
+               return PAM_SUCCESS;
+       }
+
+       if (mkdir(dirname, mode) != 0) {
+
+               _make_remark_format(ctx, PAM_TEXT_INFO,
+                                   "Creating directory: %s failed: %s",
+                                   dirname, strerror(errno));
+               _pam_log(ctx, LOG_ERR, "could not create dir: %s (%s)",
+                dirname, strerror(errno));
+                return PAM_PERM_DENIED;
+       }
+
+       return PAM_SUCCESS;
+}
+
+static int _pam_chown_homedir(struct pwb_context *ctx,
+                             const char *dirname,
+                             uid_t uid,
+                             gid_t gid)
+{
+       if (chown(dirname, uid, gid) != 0) {
+               _pam_log(ctx, LOG_ERR, "failed to chown user homedir: %s (%s)",
+                        dirname, strerror(errno));
+               return PAM_PERM_DENIED;
+       }
+
+       return PAM_SUCCESS;
+}
+
+static int _pam_mkhomedir(struct pwb_context *ctx)
+{
+       struct passwd *pwd = NULL;
+       char *token = NULL;
+       char *create_dir = NULL;
+       char *user_dir = NULL;
+       int ret;
+       const char *username;
+       mode_t mode = 0700;
+       char *safe_ptr = NULL;
+       char *p = NULL;
+
+       /* Get the username */
+       ret = pam_get_user(ctx->pamh, &username, NULL);
+       if ((ret != PAM_SUCCESS) || (!username)) {
+               _pam_log_debug(ctx, LOG_DEBUG, "can not get the username");
+               return PAM_SERVICE_ERR;
+       }
+
+       pwd = getpwnam(username);
+       if (pwd == NULL) {
+               _pam_log_debug(ctx, LOG_DEBUG, "can not get the username");
+               return PAM_USER_UNKNOWN;
+       }
+       _pam_log_debug(ctx, LOG_DEBUG, "homedir is: %s", pwd->pw_dir);
+
+       ret = _pam_create_homedir(ctx, pwd->pw_dir, 0700);
+       if (ret == PAM_SUCCESS) {
+               ret = _pam_chown_homedir(ctx, pwd->pw_dir,
+                                        pwd->pw_uid,
+                                        pwd->pw_gid);
+       }
+
+       if (ret == PAM_SUCCESS) {
+               return ret;
+       }
+
+       /* maybe we need to create parent dirs */
+       create_dir = talloc_strdup(ctx, "/");
+       if (!create_dir) {
+               return PAM_BUF_ERR;
+       }
+
+       /* find final directory */
+       user_dir = strrchr(pwd->pw_dir, '/');
+       if (!user_dir) {
+               return PAM_BUF_ERR;
+       }
+       user_dir++;
+
+       _pam_log(ctx, LOG_DEBUG, "final directory: %s", user_dir);
+
+       p = pwd->pw_dir;
+
+       while ((token = strtok_r(p, "/", &safe_ptr)) != NULL) {
+
+               mode = 0755;
+
+               p = NULL;
+
+               _pam_log_debug(ctx, LOG_DEBUG, "token is %s", token);
+
+               create_dir = talloc_asprintf_append(create_dir, "%s/", token);
+               if (!create_dir) {
+                       return PAM_BUF_ERR;
+               }
+               _pam_log_debug(ctx, LOG_DEBUG, "current_dir is %s", create_dir);
+
+               if (strcmp(token, user_dir) == 0) {
+                       _pam_log_debug(ctx, LOG_DEBUG, "assuming last directory: %s", token);
+                       mode = 0700;
+               }
+
+               ret = _pam_create_homedir(ctx, create_dir, mode);
+               if (ret) {
+                       return ret;
+               }
+       }
+
+       return _pam_chown_homedir(ctx, create_dir,
+                                 pwd->pw_uid,
+                                 pwd->pw_gid);
+}
+
 /* talk to winbindd */
 static int winbind_auth_request(struct pwb_context *ctx,
                                const char *user,
@@ -1297,37 +1512,52 @@ static int winbind_auth_request(struct pwb_context *ctx,
                                const char *member,
                                const char *cctype,
                                const int warn_pwd_expire,
-                               struct winbindd_response *p_response,
+                               struct wbcAuthErrorInfo **p_error,
+                               struct wbcLogonUserInfo **p_info,
+                               struct wbcUserPasswordPolicyInfo **p_policy,
                                time_t *pwd_last_set,
                                char **user_ret)
 {
-       struct winbindd_request request;
-       struct winbindd_response response;
-       int ret;
-       bool already_expired = false;
+       wbcErr wbc_status;
+
+       struct wbcLogonUserParams logon;
+       char membership_of[1024];
+       uid_t user_uid = -1;
+       uint32_t flags = WBFLAG_PAM_INFO3_TEXT |
+                        WBFLAG_PAM_GET_PWD_POLICY;
 
-       ZERO_STRUCT(request);
-       ZERO_STRUCT(response);
+       struct wbcLogonUserInfo *info = NULL;
+       struct wbcAuthUserInfo *user_info = NULL;
+       struct wbcAuthErrorInfo *error = NULL;
+       struct wbcUserPasswordPolicyInfo *policy = NULL;
+
+       int ret = PAM_AUTH_ERR;
+       int i;
+       const char *codes[] = {
+               "NT_STATUS_PASSWORD_EXPIRED",
+               "NT_STATUS_PASSWORD_MUST_CHANGE",
+               "NT_STATUS_INVALID_WORKSTATION",
+               "NT_STATUS_INVALID_LOGON_HOURS",
+               "NT_STATUS_ACCOUNT_EXPIRED",
+               "NT_STATUS_ACCOUNT_DISABLED",
+               "NT_STATUS_ACCOUNT_LOCKED_OUT",
+               "NT_STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT",
+               "NT_STATUS_NOLOGON_SERVER_TRUST_ACCOUNT",
+               "NT_STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT",
+               "NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND",
+               "NT_STATUS_NO_LOGON_SERVERS",
+               "NT_STATUS_WRONG_PASSWORD",
+               "NT_STATUS_ACCESS_DENIED"
+       };
 
        if (pwd_last_set) {
                *pwd_last_set = 0;
        }
 
-       strncpy(request.data.auth.user, user,
-               sizeof(request.data.auth.user)-1);
-
-       strncpy(request.data.auth.pass, pass,
-               sizeof(request.data.auth.pass)-1);
-
-       request.data.auth.krb5_cc_type[0] = '\0';
-       request.data.auth.uid = -1;
-
-       request.flags = WBFLAG_PAM_INFO3_TEXT | WBFLAG_PAM_GET_PWD_POLICY;
-
        /* Krb5 auth always has to go against the KDC of the user's realm */
 
        if (ctx->ctrl & WINBIND_KRB5_AUTH) {
-               request.flags |= WBFLAG_PAM_CONTACT_TRUSTDOM;
+               flags           |= WBFLAG_PAM_CONTACT_TRUSTDOM;
        }
 
        if (ctx->ctrl & (WINBIND_KRB5_AUTH|WINBIND_CACHED_LOGIN)) {
@@ -1337,7 +1567,7 @@ static int winbind_auth_request(struct pwb_context *ctx,
                if (pwd == NULL) {
                        return PAM_USER_UNKNOWN;
                }
-               request.data.auth.uid = pwd->pw_uid;
+               user_uid        = pwd->pw_uid;
        }
 
        if (ctx->ctrl & WINBIND_KRB5_AUTH) {
@@ -1345,38 +1575,34 @@ static int winbind_auth_request(struct pwb_context *ctx,
                _pam_log_debug(ctx, LOG_DEBUG,
                               "enabling krb5 login flag\n");
 
-               request.flags |= WBFLAG_PAM_KRB5 |
-                                WBFLAG_PAM_FALLBACK_AFTER_KRB5;
+               flags           |= WBFLAG_PAM_KRB5 |
+                                  WBFLAG_PAM_FALLBACK_AFTER_KRB5;
        }
 
        if (ctx->ctrl & WINBIND_CACHED_LOGIN) {
                _pam_log_debug(ctx, LOG_DEBUG,
                               "enabling cached login flag\n");
-               request.flags |= WBFLAG_PAM_CACHED_LOGIN;
+               flags           |= WBFLAG_PAM_CACHED_LOGIN;
        }
 
        if (user_ret) {
                *user_ret = NULL;
-               request.flags |= WBFLAG_PAM_UNIX_NAME;
+               flags           |= WBFLAG_PAM_UNIX_NAME;
        }
 
        if (cctype != NULL) {
-               strncpy(request.data.auth.krb5_cc_type, cctype,
-                       sizeof(request.data.auth.krb5_cc_type) - 1);
                _pam_log_debug(ctx, LOG_DEBUG,
                               "enabling request for a %s krb5 ccache\n",
                               cctype);
        }
 
-       request.data.auth.require_membership_of_sid[0] = '\0';
-
        if (member != NULL) {
 
-               if (!winbind_name_list_to_sid_string_list(ctx, user,
-                       member,
-                       request.data.auth.require_membership_of_sid,
-                       sizeof(request.data.auth.require_membership_of_sid))) {
+               ZERO_STRUCT(membership_of);
 
+               if (!winbind_name_list_to_sid_string_list(ctx, user, member,
+                                                         membership_of,
+                                                         sizeof(membership_of))) {
                        _pam_log_debug(ctx, LOG_ERR,
                                       "failed to serialize membership of sid "
                                       "\"%s\"\n", member);
@@ -1384,60 +1610,100 @@ static int winbind_auth_request(struct pwb_context *ctx,
                }
        }
 
-       ret = pam_winbind_request_log(ctx, WINBINDD_PAM_AUTH,
-                                     &request, &response, user);
+       ZERO_STRUCT(logon);
 
-       if (pwd_last_set) {
-               *pwd_last_set = response.data.auth.info3.pass_last_set_time;
+       logon.username                  = user;
+       logon.password                  = pass;
+
+       wbc_status = wbcAddNamedBlob(&logon.num_blobs,
+                                    &logon.blobs,
+                                    "krb5_cc_type",
+                                    0,
+                                    (uint8_t *)cctype,
+                                    strlen(cctype)+1);
+       if (!WBC_ERROR_IS_OK(wbc_status)) {
+               goto done;
+       }
+
+       wbc_status = wbcAddNamedBlob(&logon.num_blobs,
+                                    &logon.blobs,
+                                    "flags",
+                                    0,
+                                    (uint8_t *)&flags,
+                                    sizeof(flags));
+       if (!WBC_ERROR_IS_OK(wbc_status)) {
+               goto done;
+       }
+
+       wbc_status = wbcAddNamedBlob(&logon.num_blobs,
+                                    &logon.blobs,
+                                    "user_uid",
+                                    0,
+                                    (uint8_t *)&user_uid,
+                                    sizeof(user_uid));
+       if (!WBC_ERROR_IS_OK(wbc_status)) {
+               goto done;
+       }
+
+       wbc_status = wbcAddNamedBlob(&logon.num_blobs,
+                                    &logon.blobs,
+                                    "membership_of",
+                                    0,
+                                    (uint8_t *)membership_of,
+                                    sizeof(membership_of));
+       if (!WBC_ERROR_IS_OK(wbc_status)) {
+               goto done;
        }
 
-       if (p_response) {
-               /* We want to process the response in the caller. */
-               *p_response = response;
+       wbc_status = wbcLogonUser(&logon, &info, &error, &policy);
+       ret = wbc_auth_error_to_pam_error(ctx, error, wbc_status,
+                                         user, "wbcLogonUser");
+       wbcFreeMemory(logon.blobs);
+       logon.blobs = NULL;
+
+       if (info && info->info) {
+               user_info = info->info;
+       }
+
+       if (pwd_last_set && user_info) {
+               *pwd_last_set = user_info->pass_last_set_time;
+       }
+
+       if (p_info && info) {
+               *p_info = info;
+       }
+
+       if (p_policy && policy) {
+               *p_policy = policy;
+       }
+
+       if (p_error && error) {
+               /* We want to process the error in the caller. */
+               *p_error = error;
                return ret;
        }
 
-       if (ret) {
-               PAM_WB_REMARK_CHECK_RESPONSE_RET(ctx, response,
-                                                "NT_STATUS_PASSWORD_EXPIRED");
-               PAM_WB_REMARK_CHECK_RESPONSE_RET(ctx, response,
-                                                "NT_STATUS_PASSWORD_MUST_CHANGE");
-               PAM_WB_REMARK_CHECK_RESPONSE_RET(ctx, response,
-                                                "NT_STATUS_INVALID_WORKSTATION");
-               PAM_WB_REMARK_CHECK_RESPONSE_RET(ctx, response,
-                                                "NT_STATUS_INVALID_LOGON_HOURS");
-               PAM_WB_REMARK_CHECK_RESPONSE_RET(ctx, response,
-                                                "NT_STATUS_ACCOUNT_EXPIRED");
-               PAM_WB_REMARK_CHECK_RESPONSE_RET(ctx, response,
-                                                "NT_STATUS_ACCOUNT_DISABLED");
-               PAM_WB_REMARK_CHECK_RESPONSE_RET(ctx, response,
-                                                "NT_STATUS_ACCOUNT_LOCKED_OUT");
-               PAM_WB_REMARK_CHECK_RESPONSE_RET(ctx, response,
-                                                "NT_STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT");
-               PAM_WB_REMARK_CHECK_RESPONSE_RET(ctx, response,
-                                                "NT_STATUS_NOLOGON_SERVER_TRUST_ACCOUNT");
-               PAM_WB_REMARK_CHECK_RESPONSE_RET(ctx, response,
-                                                "NT_STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT");
-               PAM_WB_REMARK_CHECK_RESPONSE_RET(ctx, response,
-                                                "NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND");
-               PAM_WB_REMARK_CHECK_RESPONSE_RET(ctx, response,
-                                                "NT_STATUS_NO_LOGON_SERVERS");
-               PAM_WB_REMARK_CHECK_RESPONSE_RET(ctx, response,
-                                                "NT_STATUS_WRONG_PASSWORD");
-               PAM_WB_REMARK_CHECK_RESPONSE_RET(ctx, response,
-                                                "NT_STATUS_ACCESS_DENIED");
+       for (i=0; i<ARRAY_SIZE(codes); i++) {
+               int _ret = ret;
+               if (_pam_check_remark_auth_err(ctx, error, codes[i], &_ret)) {
+                       ret = _ret;
+                       goto done;
+               }
        }
 
-       if (ret == PAM_SUCCESS) {
+       if ((ret == PAM_SUCCESS) && user_info && policy && info) {
+
+               bool already_expired = false;
 
                /* warn a user if the password is about to expire soon */
-               _pam_warn_password_expiry(ctx, &response,
+               _pam_warn_password_expiry(ctx, user_info, policy,
                                          warn_pwd_expire,
                                          &already_expired);
 
                if (already_expired == true) {
-                       SMB_TIME_T last_set;
-                       last_set = response.data.auth.info3.pass_last_set_time;
+
+                       SMB_TIME_T last_set = user_info->pass_last_set_time;
+
                        _pam_log_debug(ctx, LOG_DEBUG,
                                       "Password has expired "
                                       "(Password was last set: %lld, "
@@ -1445,33 +1711,44 @@ static int winbind_auth_request(struct pwb_context *ctx,
                                       "%lld (now it's: %lu))\n",
                                       (long long int)last_set,
                                       (long long int)last_set +
-                                      response.data.auth.policy.expire,
+                                      policy->expire,
                                       time(NULL));
 
                        return PAM_AUTHTOK_EXPIRED;
                }
 
                /* inform about logon type */
-               _pam_warn_logon_type(ctx, user,
-                                    response.data.auth.info3.user_flgs);
+               _pam_warn_logon_type(ctx, user, user_info->user_flags);
 
                /* inform about krb5 failures */
-               _pam_warn_krb5_failure(ctx, user,
-                                      response.data.auth.info3.user_flgs);
+               _pam_warn_krb5_failure(ctx, user, user_info->user_flags);
 
                /* set some info3 info for other modules in the stack */
-               _pam_set_data_info3(ctx, &response);
+               _pam_set_data_info3(ctx, user_info);
 
                /* put krb5ccname into env */
-               _pam_setup_krb5_env(ctx, response.data.auth.krb5ccname);
+               _pam_setup_krb5_env(ctx, info);
 
                /* If winbindd returned a username, return the pointer to it
                 * here. */
-               if (user_ret && response.data.auth.unix_username[0]) {
-                       /* We have to trust it's a null terminated string. */
-                       *user_ret = strndup(response.data.auth.unix_username,
-                                   sizeof(response.data.auth.unix_username) - 1);
-               }
+               _pam_setup_unix_username(ctx, user_ret, info);
+       }
+
+ done:
+       if (logon.blobs) {
+               wbcFreeMemory(logon.blobs);
+       }
+       if (info && info->blobs) {
+               wbcFreeMemory(info->blobs);
+       }
+       if (error && !p_error) {
+               wbcFreeMemory(error);
+       }
+       if (info && !p_info) {
+               wbcFreeMemory(info);
+       }
+       if (policy && !p_policy) {
+               wbcFreeMemory(policy);
        }
 
        return ret;
@@ -1484,99 +1761,95 @@ static int winbind_chauthtok_request(struct pwb_context *ctx,
                                     const char *newpass,
                                     time_t pwd_last_set)
 {
-       struct winbindd_request request;
-       struct winbindd_response response;
-       int ret;
+       wbcErr wbc_status;
+       struct wbcChangePasswordParams params;
+       struct wbcAuthErrorInfo *error = NULL;
+       struct wbcUserPasswordPolicyInfo *policy = NULL;
+       enum wbcPasswordChangeRejectReason reject_reason = -1;
+       uint32_t flags = 0;
 
-       ZERO_STRUCT(request);
-       ZERO_STRUCT(response);
+       int i;
+       const char *codes[] = {
+               "NT_STATUS_BACKUP_CONTROLLER",
+               "NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND",
+               "NT_STATUS_NO_LOGON_SERVERS",
+               "NT_STATUS_ACCESS_DENIED",
+               "NT_STATUS_PWD_TOO_SHORT", /* TODO: tell the min pwd length ? */
+               "NT_STATUS_PWD_TOO_RECENT", /* TODO: tell the minage ? */
+               "NT_STATUS_PWD_HISTORY_CONFLICT" /* TODO: tell the history length ? */
+       };
+       int ret = PAM_AUTH_ERR;
+
+       ZERO_STRUCT(params);
 
-       if (request.data.chauthtok.user == NULL) {
-               return -2;
+       if (ctx->ctrl & WINBIND_KRB5_AUTH) {
+               flags |= WBFLAG_PAM_KRB5 |
+                        WBFLAG_PAM_CONTACT_TRUSTDOM;
        }
 
-       strncpy(request.data.chauthtok.user, user,
-               sizeof(request.data.chauthtok.user) - 1);
-
-       if (oldpass != NULL) {
-               strncpy(request.data.chauthtok.oldpass, oldpass,
-                       sizeof(request.data.chauthtok.oldpass) - 1);
-       } else {
-               request.data.chauthtok.oldpass[0] = '\0';
+       if (ctx->ctrl & WINBIND_CACHED_LOGIN) {
+               flags |= WBFLAG_PAM_CACHED_LOGIN;
        }
 
-       if (newpass != NULL) {
-               strncpy(request.data.chauthtok.newpass, newpass,
-                       sizeof(request.data.chauthtok.newpass) - 1);
-       } else {
-               request.data.chauthtok.newpass[0] = '\0';
-       }
+       params.account_name             = user;
+       params.level                    = WBC_AUTH_USER_LEVEL_PLAIN;
+       params.old_password.plaintext   = oldpass;
+       params.new_password.plaintext   = newpass;
+       params.flags                    = flags;
 
-       if (ctx->ctrl & WINBIND_KRB5_AUTH) {
-               request.flags = WBFLAG_PAM_KRB5 |
-                               WBFLAG_PAM_CONTACT_TRUSTDOM;
-       }
+       wbc_status = wbcChangeUserPasswordEx(&params, &error, &reject_reason, &policy);
+       ret = wbc_auth_error_to_pam_error(ctx, error, wbc_status,
+                                         user, "wbcChangeUserPasswordEx");
 
-       if (ctx->ctrl & WINBIND_CACHED_LOGIN) {
-               request.flags |= WBFLAG_PAM_CACHED_LOGIN;
+       if (WBC_ERROR_IS_OK(wbc_status)) {
+               _pam_log(ctx, LOG_NOTICE,
+                        "user '%s' password changed", user);
+               return PAM_SUCCESS;
        }
 
-       ret = pam_winbind_request_log(ctx, WINBINDD_PAM_CHAUTHTOK,
-                                     &request, &response, user);
-
-       if (ret == PAM_SUCCESS) {
+       if (!error) {
+               wbcFreeMemory(policy);
                return ret;
        }
 
-       PAM_WB_REMARK_CHECK_RESPONSE_RET(ctx, response,
-                                        "NT_STATUS_BACKUP_CONTROLLER");
-       PAM_WB_REMARK_CHECK_RESPONSE_RET(ctx, response,
-                                        "NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND");
-       PAM_WB_REMARK_CHECK_RESPONSE_RET(ctx, response,
-                                        "NT_STATUS_NO_LOGON_SERVERS");
-       PAM_WB_REMARK_CHECK_RESPONSE_RET(ctx, response,
-                                        "NT_STATUS_ACCESS_DENIED");
-
-       /* TODO: tell the min pwd length ? */
-       PAM_WB_REMARK_CHECK_RESPONSE_RET(ctx, response,
-                                        "NT_STATUS_PWD_TOO_SHORT");
-
-       /* TODO: tell the minage ? */
-       PAM_WB_REMARK_CHECK_RESPONSE_RET(ctx, response,
-                                        "NT_STATUS_PWD_TOO_RECENT");
-
-       /* TODO: tell the history length ? */
-       PAM_WB_REMARK_CHECK_RESPONSE_RET(ctx, response,
-                                        "NT_STATUS_PWD_HISTORY_CONFLICT");
+       for (i=0; i<ARRAY_SIZE(codes); i++) {
+               int _ret = ret;
+               if (_pam_check_remark_auth_err(ctx, error, codes[i], &_ret)) {
+                       ret = _ret;
+                       goto done;
+               }
+       }
 
-       if (!strcasecmp(response.data.auth.nt_status_string,
+       if (!strcasecmp(error->nt_string,
                        "NT_STATUS_PASSWORD_RESTRICTION")) {
 
                char *pwd_restriction_string = NULL;
-               SMB_TIME_T min_pwd_age;
-               uint32_t reject_reason = response.data.auth.reject_reason;
-               min_pwd_age = response.data.auth.policy.min_passwordage;
+               SMB_TIME_T min_pwd_age = 0;
+
+               if (policy) {
+                       min_pwd_age     = policy->min_passwordage;
+               }
 
                /* FIXME: avoid to send multiple PAM messages after another */
                switch (reject_reason) {
                        case -1:
                                break;
-                       case SAMR_REJECT_OTHER:
+                       case WBC_PWD_CHANGE_REJECT_OTHER:
                                if ((min_pwd_age > 0) &&
                                    (pwd_last_set + min_pwd_age > time(NULL))) {
                                        PAM_WB_REMARK_DIRECT(ctx,
                                             "NT_STATUS_PWD_TOO_RECENT");
                                }
                                break;
-                       case SAMR_REJECT_TOO_SHORT:
+                       case WBC_PWD_CHANGE_REJECT_TOO_SHORT:
                                PAM_WB_REMARK_DIRECT(ctx,
                                        "NT_STATUS_PWD_TOO_SHORT");
                                break;
-                       case SAMR_REJECT_IN_HISTORY:
+                       case WBC_PWD_CHANGE_REJECT_IN_HISTORY:
                                PAM_WB_REMARK_DIRECT(ctx,
                                        "NT_STATUS_PWD_HISTORY_CONFLICT");
                                break;
-                       case SAMR_REJECT_COMPLEXITY:
+                       case WBC_PWD_CHANGE_REJECT_COMPLEXITY:
                                _make_remark(ctx, PAM_ERROR_MSG,
                                             "Password does not meet "
                                             "complexity requirements");
@@ -1590,13 +1863,16 @@ static int winbind_chauthtok_request(struct pwb_context *ctx,
                }
 
                pwd_restriction_string =
-                       _pam_compose_pwd_restriction_string(&response);
+                       _pam_compose_pwd_restriction_string(ctx, policy);
                if (pwd_restriction_string) {
                        _make_remark(ctx, PAM_ERROR_MSG,
                                     pwd_restriction_string);
-                       SAFE_FREE(pwd_restriction_string);
+                       TALLOC_FREE(pwd_restriction_string);
                }
        }
+ done:
+       wbcFreeMemory(error);
+       wbcFreeMemory(policy);
 
        return ret;
 }
@@ -1616,29 +1892,26 @@ static int valid_user(struct pwb_context *ctx,
         * sure it's really a winbind user, this is important when stacking PAM
         * modules in the 'account' or 'password' facility. */
 
+       wbcErr wbc_status;
        struct passwd *pwd = NULL;
-       struct winbindd_request request;
-       struct winbindd_response response;
-       int ret;
-
-       ZERO_STRUCT(request);
-       ZERO_STRUCT(response);
+       struct passwd *wb_pwd = NULL;
 
        pwd = getpwnam(user);
        if (pwd == NULL) {
                return 1;
        }
 
-       strncpy(request.data.username, user,
-               sizeof(request.data.username) - 1);
-
-       ret = pam_winbind_request_log(ctx, WINBINDD_GETPWNAM,
-                                     &request, &response, user);
+       wbc_status = wbcGetpwnam(user, &wb_pwd);
+       wbcFreeMemory(wb_pwd);
+       if (!WBC_ERROR_IS_OK(wbc_status)) {
+               _pam_log(ctx, LOG_DEBUG, "valid_user: wbcGetpwnam gave %s\n",
+                       wbcErrorString(wbc_status));
+       }
 
-       switch (ret) {
-               case PAM_USER_UNKNOWN:
+       switch (wbc_status) {
+               case WBC_ERR_UNKNOWN_USER:
                        return 1;
-               case PAM_SUCCESS:
+               case WBC_ERR_SUCCESS:
                        return 0;
                default:
                        break;
@@ -1846,12 +2119,13 @@ static const char *get_conf_item_string(struct pwb_context *ctx,
        if (ctx->dict) {
                char *key = NULL;
 
-               if (!asprintf(&key, "global:%s", item)) {
+               key = talloc_asprintf(ctx, "global:%s", item);
+               if (!key) {
                        goto out;
                }
 
                parm_opt = iniparser_getstr(ctx->dict, key);
-               SAFE_FREE(key);
+               TALLOC_FREE(key);
 
                _pam_log_debug(ctx, LOG_INFO, "CONFIG file: %s '%s'\n",
                               item, parm_opt);
@@ -1893,12 +2167,13 @@ static int get_config_item_int(struct pwb_context *ctx,
        if (ctx->dict) {
                char *key = NULL;
 
-               if (!asprintf(&key, "global:%s", item)) {
+               key = talloc_asprintf(ctx, "global:%s", item);
+               if (!key) {
                        goto out;
                }
 
                parm_opt = iniparser_getint(ctx->dict, key, -1);
-               SAFE_FREE(key);
+               TALLOC_FREE(key);
 
                _pam_log_debug(ctx, LOG_INFO,
                               "CONFIG file: %s '%d'\n",
@@ -1948,20 +2223,25 @@ static int get_warn_pwd_expire_from_config(struct pwb_context *ctx)
 
 static char winbind_get_separator(struct pwb_context *ctx)
 {
-       struct winbindd_request request;
-       struct winbindd_response response;
+       wbcErr wbc_status;
+       static struct wbcInterfaceDetails *details = NULL;
 
-       ZERO_STRUCT(request);
-       ZERO_STRUCT(response);
+       wbc_status = wbcInterfaceDetails(&details);
+       if (!WBC_ERROR_IS_OK(wbc_status)) {
+               _pam_log(ctx, LOG_ERR,
+                        "Could not retrieve winbind interface details: %s",
+                        wbcErrorString(wbc_status));
+               return '\0';
+       }
 
-       if (pam_winbind_request_log(ctx, WINBINDD_INFO,
-                                   &request, &response, NULL)) {
+       if (!details) {
                return '\0';
        }
 
-       return response.data.info.winbind_separator;
+       return details->winbind_separator;
 }
 
+
 /**
  * Convert a upn to a name.
  *
@@ -1974,12 +2254,12 @@ static char winbind_get_separator(struct pwb_context *ctx)
 static char* winbind_upn_to_username(struct pwb_context *ctx,
                                     const char *upn)
 {
-       struct winbindd_request req;
-       struct winbindd_response resp;
-       int retval;
-       char *account_name;
-       int account_name_len;
        char sep;
+       wbcErr wbc_status = WBC_ERR_UNKNOWN_FAILURE;
+       struct wbcDomainSid sid;
+       enum wbcSidType type;
+       char *domain;
+       char *name;
 
        /* This cannot work when the winbind separator = @ */
 
@@ -1990,35 +2270,19 @@ static char* winbind_upn_to_username(struct pwb_context *ctx,
 
        /* Convert the UPN to a SID */
 
-       ZERO_STRUCT(req);
-       ZERO_STRUCT(resp);
-
-       strncpy(req.data.name.dom_name, "",
-               sizeof(req.data.name.dom_name) - 1);
-       strncpy(req.data.name.name, upn,
-               sizeof(req.data.name.name) - 1);
-       retval = pam_winbind_request_log(ctx, WINBINDD_LOOKUPNAME,
-                                        &req, &resp, upn);
-       if (retval != PAM_SUCCESS) {
+       wbc_status = wbcLookupName("", upn, &sid, &type);
+       if (!WBC_ERROR_IS_OK(wbc_status)) {
                return NULL;
        }
 
        /* Convert the the SID back to the sAMAccountName */
 
-       ZERO_STRUCT(req);
-       strncpy(req.data.sid, resp.data.sid.sid, sizeof(req.data.sid)-1);
-       ZERO_STRUCT(resp);
-       retval =  pam_winbind_request_log(ctx, WINBINDD_LOOKUPSID,
-                                         &req, &resp, upn);
-       if (retval != PAM_SUCCESS) {
+       wbc_status = wbcLookupSid(&sid, &domain, &name, &type);
+       if (!WBC_ERROR_IS_OK(wbc_status)) {
                return NULL;
        }
 
-       account_name_len = asprintf(&account_name, "%s\\%s",
-                                   resp.data.name.dom_name,
-                                   resp.data.name.name);
-
-       return account_name;
+       return talloc_asprintf(ctx, "%s\\%s", domain, name);
 }
 
 PAM_EXTERN
@@ -2087,7 +2351,7 @@ int pam_sm_authenticate(pam_handle_t *pamh, int flags,
                                                         real_username);
                if (samaccountname) {
                        free(real_username);
-                       real_username = samaccountname;
+                       real_username = strdup(samaccountname);
                }
        }
 
@@ -2119,7 +2383,8 @@ int pam_sm_authenticate(pam_handle_t *pamh, int flags,
 
        /* Now use the username to look up password */
        retval = winbind_auth_request(ctx, real_username, password,
-                                     member, cctype, warn_pwd_expire, NULL,
+                                     member, cctype, warn_pwd_expire,
+                                     NULL, NULL, NULL,
                                      NULL, &username_ret);
 
        if (retval == PAM_NEW_AUTHTOK_REQD ||
@@ -2127,7 +2392,8 @@ int pam_sm_authenticate(pam_handle_t *pamh, int flags,
 
                char *new_authtok_required_during_auth = NULL;
 
-               if (!asprintf(&new_authtok_required, "%d", retval)) {
+               new_authtok_required = talloc_asprintf(NULL, "%d", retval);
+               if (!new_authtok_required) {
                        retval = PAM_BUF_ERR;
                        goto out;
                }
@@ -2138,7 +2404,8 @@ int pam_sm_authenticate(pam_handle_t *pamh, int flags,
 
                retval = PAM_SUCCESS;
 
-               if (!asprintf(&new_authtok_required_during_auth, "%d", true)) {
+               new_authtok_required_during_auth = talloc_asprintf(NULL, "%d", true);
+               if (!new_authtok_required_during_auth) {
                        retval = PAM_BUF_ERR;
                        goto out;
                }
@@ -2172,7 +2439,7 @@ out:
 
        _PAM_LOG_FUNCTION_LEAVE("pam_sm_authenticate", ctx, retval);
 
-       _pam_winbind_free_context(ctx);
+       TALLOC_FREE(ctx);
 
        return retval;
 }
@@ -2220,7 +2487,7 @@ int pam_sm_setcred(pam_handle_t *pamh, int flags,
 
        _PAM_LOG_FUNCTION_LEAVE("pam_sm_setcred", ctx, ret);
 
-       _pam_winbind_free_context(ctx);
+       TALLOC_FREE(ctx);
 
        return ret;
 }
@@ -2321,7 +2588,7 @@ int pam_sm_acct_mgmt(pam_handle_t *pamh, int flags,
 
        _PAM_LOG_FUNCTION_LEAVE("pam_sm_acct_mgmt", ctx, ret);
 
-       _pam_winbind_free_context(ctx);
+       TALLOC_FREE(ctx);
 
        return ret;
 }
@@ -2330,7 +2597,7 @@ PAM_EXTERN
 int pam_sm_open_session(pam_handle_t *pamh, int flags,
                        int argc, const char **argv)
 {
-       int ret = PAM_SYSTEM_ERR;
+       int ret = PAM_SUCCESS;
        struct pwb_context *ctx = NULL;
 
        ret = _pam_winbind_init_context(pamh, flags, argc, argv, &ctx);
@@ -2340,12 +2607,14 @@ int pam_sm_open_session(pam_handle_t *pamh, int flags,
 
        _PAM_LOG_FUNCTION_ENTER("pam_sm_open_session", ctx);
 
-       ret = PAM_SUCCESS;
-
+       if (ctx->ctrl & WINBIND_MKHOMEDIR) {
+               /* check and create homedir */
+               ret = _pam_mkhomedir(ctx);
+       }
  out:
        _PAM_LOG_FUNCTION_LEAVE("pam_sm_open_session", ctx, ret);
 
-       _pam_winbind_free_context(ctx);
+       TALLOC_FREE(ctx);
 
        return ret;
 }
@@ -2356,6 +2625,7 @@ int pam_sm_close_session(pam_handle_t *pamh, int flags,
 {
        int retval = PAM_SUCCESS;
        struct pwb_context *ctx = NULL;
+       struct wbcLogoffUserParams logoff;
 
        retval = _pam_winbind_init_context(pamh, flags, argc, argv, &ctx);
        if (retval) {
@@ -2372,15 +2642,15 @@ int pam_sm_close_session(pam_handle_t *pamh, int flags,
        if (ctx->ctrl & WINBIND_KRB5_AUTH) {
 
                /* destroy the ccache here */
-               struct winbindd_request request;
-               struct winbindd_response response;
+
+               wbcErr wbc_status;
+               struct wbcAuthErrorInfo *error = NULL;
+
+               uint32_t flags = 0;
                const char *user;
                const char *ccname = NULL;
                struct passwd *pwd = NULL;
 
-               ZERO_STRUCT(request);
-               ZERO_STRUCT(response);
-
                retval = pam_get_user(pamh, &user, "Username: ");
                if (retval) {
                        _pam_log(ctx, LOG_ERR,
@@ -2404,34 +2674,70 @@ int pam_sm_close_session(pam_handle_t *pamh, int flags,
                                       "user has no KRB5CCNAME environment");
                }
 
-               strncpy(request.data.logoff.user, user,
-                       sizeof(request.data.logoff.user) - 1);
-
-               if (ccname) {
-                       strncpy(request.data.logoff.krb5ccname, ccname,
-                               sizeof(request.data.logoff.krb5ccname) - 1);
-               }
-
                pwd = getpwnam(user);
                if (pwd == NULL) {
                        retval = PAM_USER_UNKNOWN;
                        goto out;
                }
-               request.data.logoff.uid = pwd->pw_uid;
 
-               request.flags = WBFLAG_PAM_KRB5 |
-                               WBFLAG_PAM_CONTACT_TRUSTDOM;
+               flags = WBFLAG_PAM_KRB5 |
+                       WBFLAG_PAM_CONTACT_TRUSTDOM;
+
+               ZERO_STRUCT(logoff);
+
+               logoff.username         = user;
 
-               retval = pam_winbind_request_log(ctx,
-                                                WINBINDD_PAM_LOGOFF,
-                                                &request, &response, user);
+               wbc_status = wbcAddNamedBlob(&logoff.num_blobs,
+                                            &logoff.blobs,
+                                            "ccfilename",
+                                            0,
+                                            (uint8_t *)ccname,
+                                            strlen(ccname)+1);
+               if (!WBC_ERROR_IS_OK(wbc_status)) {
+                       goto out;
+               }
+
+               wbc_status = wbcAddNamedBlob(&logoff.num_blobs,
+                                            &logoff.blobs,
+                                            "flags",
+                                            0,
+                                            (uint8_t *)&flags,
+                                            sizeof(flags));
+               if (!WBC_ERROR_IS_OK(wbc_status)) {
+                       goto out;
+               }
+
+               wbc_status = wbcAddNamedBlob(&logoff.num_blobs,
+                                            &logoff.blobs,
+                                            "user_uid",
+                                            0,
+                                            (uint8_t *)&pwd->pw_uid,
+                                            sizeof(pwd->pw_uid));
+               if (!WBC_ERROR_IS_OK(wbc_status)) {
+                       goto out;
+               }
+
+               wbc_status = wbcLogoffUserEx(&logoff, &error);
+               retval = wbc_auth_error_to_pam_error(ctx, error, wbc_status,
+                                                    user, "wbcLogoffUser");
+               wbcFreeMemory(error);
+               wbcFreeMemory(logoff.blobs);
+
+               if (!WBC_ERROR_IS_OK(wbc_status)) {
+                       _pam_log(ctx, LOG_INFO,
+                                "failed to logoff user %s: %s\n",
+                                        user, wbcErrorString(wbc_status));
+               }
        }
 
 out:
+       if (logoff.blobs) {
+               wbcFreeMemory(logoff.blobs);
+       }
 
        _PAM_LOG_FUNCTION_LEAVE("pam_sm_close_session", ctx, retval);
 
-       _pam_winbind_free_context(ctx);
+       TALLOC_FREE(ctx);
 
        return retval;
 }
@@ -2503,11 +2809,9 @@ int pam_sm_chauthtok(pam_handle_t * pamh, int flags,
 
        int retry = 0;
        char *username_ret = NULL;
-       struct winbindd_response response;
+       struct wbcAuthErrorInfo *error = NULL;
        struct pwb_context *ctx = NULL;
 
-       ZERO_STRUCT(response);
-
        ret = _pam_winbind_init_context(pamh, flags, argc, argv, &ctx);
        if (ret) {
                goto out;
@@ -2560,16 +2864,15 @@ int pam_sm_chauthtok(pam_handle_t * pamh, int flags,
                time_t pwdlastset_prelim = 0;
 
                /* instruct user what is happening */
-#define greeting "Changing password for "
-               Announce = (char *) malloc(sizeof(greeting) + strlen(user));
-               if (Announce == NULL) {
+
+#define greeting "Changing password for"
+               Announce = talloc_asprintf(ctx, "%s %s", greeting, user);
+               if (!Announce) {
                        _pam_log(ctx, LOG_CRIT,
                                 "password - out of memory");
                        ret = PAM_BUF_ERR;
                        goto out;
                }
-               (void) strcpy(Announce, greeting);
-               (void) strcpy(Announce + sizeof(greeting) - 1, user);
 #undef greeting
 
                lctrl = ctx->ctrl | WINBIND__OLD_PASSWORD;
@@ -2578,6 +2881,7 @@ int pam_sm_chauthtok(pam_handle_t * pamh, int flags,
                                                "(current) NT password: ",
                                                NULL,
                                                (const char **) &pass_old);
+               TALLOC_FREE(Announce);
                if (ret != PAM_SUCCESS) {
                        _pam_log(ctx, LOG_NOTICE,
                                 "password - (old) token not obtained");
@@ -2587,7 +2891,8 @@ int pam_sm_chauthtok(pam_handle_t * pamh, int flags,
                /* verify that this is the password for this user */
 
                ret = winbind_auth_request(ctx, user, pass_old,
-                                          NULL, NULL, 0, &response,
+                                          NULL, NULL, 0,
+                                          &error, NULL, NULL,
                                           &pwdlastset_prelim, NULL);
 
                if (ret != PAM_ACCT_EXPIRED &&
@@ -2696,6 +3001,8 @@ int pam_sm_chauthtok(pam_handle_t * pamh, int flags,
                        const char *member = NULL;
                        const char *cctype = NULL;
                        int warn_pwd_expire;
+                       struct wbcLogonUserInfo *info = NULL;
+                       struct wbcUserPasswordPolicyInfo *policy = NULL;
 
                        member = get_member_from_config(ctx);
                        cctype = get_krb5_cc_type_from_config(ctx);
@@ -2710,7 +3017,8 @@ int pam_sm_chauthtok(pam_handle_t * pamh, int flags,
                         * */
 
                        ret = winbind_auth_request(ctx, user, pass_new,
-                                                  member, cctype, 0, &response,
+                                                  member, cctype, 0,
+                                                  &error, &info, &policy,
                                                   NULL, &username_ret);
                        _pam_overwrite(pass_new);
                        _pam_overwrite(pass_old);
@@ -2718,19 +3026,24 @@ int pam_sm_chauthtok(pam_handle_t * pamh, int flags,
 
                        if (ret == PAM_SUCCESS) {
 
+                               struct wbcAuthUserInfo *user_info = NULL;
+
+                               if (info && info->info) {
+                                       user_info = info->info;
+                               }
+
                                /* warn a user if the password is about to
                                 * expire soon */
-                               _pam_warn_password_expiry(ctx, &response,
+                               _pam_warn_password_expiry(ctx, user_info, policy,
                                                          warn_pwd_expire,
                                                          NULL);
 
                                /* set some info3 info for other modules in the
                                 * stack */
-                               _pam_set_data_info3(ctx, &response);
+                               _pam_set_data_info3(ctx, user_info);
 
                                /* put krb5ccname into env */
-                               _pam_setup_krb5_env(ctx,
-                                                   response.data.auth.krb5ccname);
+                               _pam_setup_krb5_env(ctx, info);
 
                                if (username_ret) {
                                        pam_set_item(pamh, PAM_USER,
@@ -2740,6 +3053,9 @@ int pam_sm_chauthtok(pam_handle_t * pamh, int flags,
                                                       username_ret);
                                        free(username_ret);
                                }
+
+                               wbcFreeMemory(info);
+                               wbcFreeMemory(policy);
                        }
 
                        goto out;
@@ -2749,18 +3065,28 @@ int pam_sm_chauthtok(pam_handle_t * pamh, int flags,
        }
 
 out:
+       {
+               /* Deal with offline errors. */
+               int i;
+               const char *codes[] = {
+                       "NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND",
+                       "NT_STATUS_NO_LOGON_SERVERS",
+                       "NT_STATUS_ACCESS_DENIED"
+               };
+
+               for (i=0; i<ARRAY_SIZE(codes); i++) {
+                       int _ret;
+                       if (_pam_check_remark_auth_err(ctx, error, codes[i], &_ret)) {
+                               break;
+                       }
+               }
+       }
 
-       /* Deal with offline errors. */
-       PAM_WB_REMARK_CHECK_RESPONSE(ctx, response,
-                                    "NT_STATUS_NO_LOGON_SERVERS");
-       PAM_WB_REMARK_CHECK_RESPONSE(ctx, response,
-                                    "NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND");
-       PAM_WB_REMARK_CHECK_RESPONSE(ctx, response,
-                                    "NT_STATUS_ACCESS_DENIED");
+       wbcFreeMemory(error);
 
        _PAM_LOG_FUNCTION_LEAVE("pam_sm_chauthtok", ctx, ret);
 
-       _pam_winbind_free_context(ctx);
+       TALLOC_FREE(ctx);
 
        return ret;
 }
index 6dba127cdc3a6f8717c25e03a7fcb7106b8bebcc..cb6f450ccb7ded1c3c6fe202de08cda34288cebb 100644 (file)
@@ -7,6 +7,8 @@
 #include "../lib/replace/replace.h"
 #include "system/syslog.h"
 #include "system/time.h"
+#include <talloc.h>
+#include "libwbclient/wbclient.h"
 
 #define MODULE_NAME "pam_winbind"
 #define PAM_SM_AUTH
@@ -97,6 +99,7 @@ do {                             \
 #define WINBIND_SILENT                 0x00000800
 #define WINBIND_DEBUG_STATE            0x00001000
 #define WINBIND_WARN_PWD_EXPIRE                0x00002000
+#define WINBIND_MKHOMEDIR              0x00004000
 
 /*
  * here is the string to inform the user that the new passwords they
@@ -133,73 +136,11 @@ do {                             \
        };\
 };
 
-#define PAM_WB_REMARK_DIRECT_RET(h,f,x)\
-{\
-       const char *error_string = NULL; \
-       error_string = _get_ntstatus_error_string(x);\
-       if (error_string != NULL) {\
-               _make_remark(h, f, PAM_ERROR_MSG, error_string);\
-               return ret;\
-       };\
-       _make_remark(h, f, PAM_ERROR_MSG, x);\
-       return ret;\
-};
-
-#define PAM_WB_REMARK_CHECK_RESPONSE(c,x,y)\
-{\
-       const char *ntstatus = x.data.auth.nt_status_string; \
-       const char *error_string = NULL; \
-       if (!strcasecmp(ntstatus,y)) {\
-               error_string = _get_ntstatus_error_string(y);\
-               if (error_string != NULL) {\
-                       _make_remark(c, PAM_ERROR_MSG, error_string);\
-               };\
-               if (x.data.auth.error_string[0] != '\0') {\
-                       _make_remark(c, PAM_ERROR_MSG, x.data.auth.error_string);\
-               };\
-               _make_remark(c, PAM_ERROR_MSG, y);\
-       };\
-};
-
-#define PAM_WB_REMARK_CHECK_RESPONSE_RET(c,x,y)\
-{\
-       const char *ntstatus = x.data.auth.nt_status_string; \
-       const char *error_string = NULL; \
-       if (!strcasecmp(ntstatus,y)) {\
-               error_string = _get_ntstatus_error_string(y);\
-               if (error_string != NULL) {\
-                       _make_remark(c, PAM_ERROR_MSG, error_string);\
-                       return ret;\
-               };\
-               if (x.data.auth.error_string[0] != '\0') {\
-                       _make_remark(c, PAM_ERROR_MSG, x.data.auth.error_string);\
-                       return ret;\
-               };\
-               _make_remark(c, PAM_ERROR_MSG, y);\
-               return ret;\
-       };\
-};
-
-/* from samr.idl */
-#define DOMAIN_PASSWORD_COMPLEX                0x00000001
-
-#define SAMR_REJECT_OTHER              0x00000000
-#define SAMR_REJECT_TOO_SHORT          0x00000001
-#define SAMR_REJECT_IN_HISTORY         0x00000002
-#define SAMR_REJECT_COMPLEXITY         0x00000005
-
-#define ACB_PWNOEXP                    0x00000200
-
-/* from netlogon.idl */
-#define NETLOGON_CACHED_ACCOUNT                0x00000004
-#define NETLOGON_GRACE_LOGON           0x01000000
-
-/* from include/rpc_netlogon.h */
 #define LOGON_KRB5_FAIL_CLOCK_SKEW     0x02000000
 
-#define PAM_WB_CACHED_LOGON(x) (x & NETLOGON_CACHED_ACCOUNT)
+#define PAM_WB_CACHED_LOGON(x) (x & WBC_AUTH_USER_INFO_CACHED_ACCOUNT)
 #define PAM_WB_KRB5_CLOCK_SKEW(x) (x & LOGON_KRB5_FAIL_CLOCK_SKEW)
-#define PAM_WB_GRACE_LOGON(x)  ((NETLOGON_CACHED_ACCOUNT|NETLOGON_GRACE_LOGON) == ( x & (NETLOGON_CACHED_ACCOUNT|NETLOGON_GRACE_LOGON)))
+#define PAM_WB_GRACE_LOGON(x)  ((WBC_AUTH_USER_INFO_CACHED_ACCOUNT|WBC_AUTH_USER_INFO_GRACE_LOGON) == ( x & (WBC_AUTH_USER_INFO_CACHED_ACCOUNT|WBC_AUTH_USER_INFO_GRACE_LOGON)))
 
 struct pwb_context {
        pam_handle_t *pamh;
@@ -209,3 +150,8 @@ struct pwb_context {
        dictionary *dict;
        uint32_t ctrl;
 };
+
+#define TALLOC_FREE(ctx) do { if ((ctx) != NULL) {talloc_free(ctx); ctx=NULL;} } while(0)
+#define TALLOC_ZERO_P(ctx, type) (type *)_talloc_zero(ctx, sizeof(type), #type)
+#define TALLOC_P(ctx, type) (type *)talloc_named_const(ctx, sizeof(type), #type)
+
index 60524d1d1ba0aae06ea720cf8236f837255c1794..fc49be4314b1d8e82fc063ce16823f88e0875a3f 100644 (file)
@@ -538,8 +538,8 @@ static bool wbinfo_dsgetdcname(const char *domain_name, uint32_t flags)
        ZERO_STRUCT(request);
        ZERO_STRUCT(response);
 
-       fstrcpy(request.domain_name, domain_name);
-       request.flags = flags;
+       fstrcpy(request.data.dsgetdcname.domain_name, domain_name);
+       request.data.dsgetdcname.flags = flags;
 
        request.flags |= DS_DIRECTORY_SERVICE_REQUIRED;
 
@@ -553,7 +553,15 @@ static bool wbinfo_dsgetdcname(const char *domain_name, uint32_t flags)
 
        /* Display response */
 
-       d_printf("%s\n", response.data.dc_name);
+       d_printf("%s\n", response.data.dsgetdcname.dc_unc);
+       d_printf("%s\n", response.data.dsgetdcname.dc_address);
+       d_printf("%d\n", response.data.dsgetdcname.dc_address_type);
+       d_printf("%s\n", response.data.dsgetdcname.domain_guid);
+       d_printf("%s\n", response.data.dsgetdcname.domain_name);
+       d_printf("%s\n", response.data.dsgetdcname.forest_name);
+       d_printf("0x%08x\n", response.data.dsgetdcname.dc_flags);
+       d_printf("%s\n", response.data.dsgetdcname.dc_site_name);
+       d_printf("%s\n", response.data.dsgetdcname.client_site_name);
 
        return true;
 }
index 990c2cae50704928e8ad56b289a48262b4d64711..b9e35bdec5998bf7c6d31d57ab4b84a1ac88aa9b 100644 (file)
@@ -1,7 +1,7 @@
 /*
    Unix SMB/CIFS implementation.
    kerberos locator plugin
-   Copyright (C) Guenther Deschner 2007
+   Copyright (C) Guenther Deschner 2007-2008
 
    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
@@ -18,6 +18,7 @@
 */
 
 #include "nsswitch/winbind_client.h"
+#include "libwbclient/wbclient.h"
 
 #ifndef DEBUG_KRB5
 #undef DEBUG_KRB5
@@ -244,37 +245,50 @@ static void smb_krb5_locator_close(void *private_data)
 
 static bool ask_winbind(const char *realm, char **dcname)
 {
-       NSS_STATUS status;
-       struct winbindd_request request;
-       struct winbindd_response response;
+       wbcErr wbc_status;
+       const char *dc = NULL;
+       struct wbcDomainControllerInfoEx *dc_info = NULL;
+       uint32_t flags;
 
-       ZERO_STRUCT(request);
-       ZERO_STRUCT(response);
+       flags = WBC_LOOKUP_DC_KDC_REQUIRED |
+               WBC_LOOKUP_DC_IS_DNS_NAME |
+               WBC_LOOKUP_DC_RETURN_DNS_NAME |
+               WBC_LOOKUP_DC_IP_REQUIRED;
 
-       request.flags = 0x40020600;
-                       /* DS_KDC_REQUIRED |
-                       DS_IS_DNS_NAME |
-                       DS_RETURN_DNS_NAME |
-                       DS_IP_REQUIRED */
+       wbc_status = wbcLookupDomainControllerEx(realm, NULL, NULL, flags, &dc_info);
 
-       strncpy(request.domain_name, realm,
-               sizeof(request.domain_name)-1);
-
-       status = winbindd_request_response(WINBINDD_DSGETDCNAME,
-                                          &request, &response);
-       if (status != NSS_STATUS_SUCCESS) {
+       if (!WBC_ERROR_IS_OK(wbc_status)) {
 #ifdef DEBUG_KRB5
                fprintf(stderr,"[%5u]: smb_krb5_locator_lookup: failed with: %s\n",
-                       (unsigned int)getpid(), nss_err_str(status));
+                       (unsigned int)getpid(), wbcErrorString(wbc_status));
 #endif
                return false;
        }
 
-       *dcname = strdup(response.data.dc_name);
+       if (dc_info->dc_address) {
+               dc = dc_info->dc_address;
+               if (dc[0] == '\\') dc++;
+               if (dc[0] == '\\') dc++;
+       }
+
+       if (!dc && dc_info->dc_unc) {
+               dc = dc_info->dc_unc;
+               if (dc[0] == '\\') dc++;
+               if (dc[0] == '\\') dc++;
+       }
+
+       if (!dc) {
+               wbcFreeMemory(dc_info);
+               return false;
+       }
+
+       *dcname = strdup(dc);
        if (!*dcname) {
+               wbcFreeMemory(dc_info);
                return false;
        }
 
+       wbcFreeMemory(dc_info);
        return true;
 }
 
index e81813c77b37d225c0cec87a184a83bbf5483283..ff52dbddafcbfba5447b6050cb152727eb3c4eda 100644 (file)
@@ -313,6 +313,12 @@ struct winbindd_request {
                        uint32_t initial_blob_len; /* blobs in extra_data */
                        uint32_t challenge_blob_len;
                } ccache_ntlm_auth;
+               struct {
+                       fstring domain_name;
+                       fstring domain_guid;
+                       fstring site_name;
+                       uint32_t flags;
+               } dsgetdcname;
 
                /* padding -- needed to fix alignment between 32bit and 64bit libs.
                   The size is the sizeof the union without the padding aligned on 
@@ -453,6 +459,17 @@ struct winbindd_response {
                struct {
                        uint32_t auth_blob_len; /* blob in extra_data */
                } ccache_ntlm_auth;
+               struct {
+                       fstring dc_unc;
+                       fstring dc_address;
+                       uint32_t dc_address_type;
+                       fstring domain_guid;
+                       fstring domain_name;
+                       fstring forest_name;
+                       uint32_t dc_flags;
+                       fstring dc_site_name;
+                       fstring client_site_name;
+               } dsgetdcname;
        } data;
 
        /* Variable length return data */
index db9e990e64fc07896cf08787ba460a217647b2c9..1191c3d3aa690905a0a7b11f79d0ebb61b0cc174 100644 (file)
@@ -341,7 +341,7 @@ struct global {
        int iKeepalive;
        int iminreceivefile;
        struct param_opt_struct *param_opt;
-       int cups_timeout;
+       int cups_connection_timeout;
 };
 
 static struct global Globals;
@@ -2597,10 +2597,10 @@ static struct parm_struct parm_table[] = {
                .flags          = FLAG_ADVANCED | FLAG_PRINT | FLAG_GLOBAL,
        },
        {
-               .label          = "cups timeout",
+               .label          = "cups connection timeout",
                .type           = P_INTEGER,
                .p_class        = P_GLOBAL,
-               .ptr            = &Globals.cups_timeout,
+               .ptr            = &Globals.cups_connection_timeout,
                .special        = NULL,
                .enum_list      = NULL,
                .flags          = FLAG_ADVANCED,
@@ -4572,6 +4572,54 @@ static void init_printer_values(struct service *pService)
        }
 }
 
+/**
+ * Free the allocated data for one parameter for a given share.
+ */
+static void free_parameter(int snum, struct parm_struct parm)
+{
+       void *parm_ptr;
+
+       if (parm.ptr == NULL); {
+               return;
+       }
+
+       if (snum < 0) {
+               parm_ptr = parm.ptr;
+       } else if (parm.p_class != P_LOCAL) {
+               return;
+       } else {
+               parm_ptr = lp_local_ptr(snum, parm.ptr);
+       }
+
+       if ((parm.type == P_STRING) ||
+           (parm.type == P_USTRING))
+       {
+               string_free((char**)parm_ptr);
+       } else if (parm.type == P_LIST) {
+               TALLOC_FREE(*((char***)parm_ptr));
+       }
+}
+
+/**
+ * Free the allocated parameter data for a share.
+ */
+static void free_parameters(int snum)
+{
+       uint32_t i;
+
+       for (i=0; parm_table[i].label; i++) {
+               free_parameter(snum, parm_table[i]);
+       }
+}
+
+/**
+ * Free the allocated global parameters.
+ */
+static void free_global_parameters(void)
+{
+       free_parameters(GLOBAL_SECTION_SNUM);
+}
+
 /***************************************************************************
  Initialise the global parameter structure.
 ***************************************************************************/
@@ -4596,14 +4644,7 @@ static void init_globals(bool first_time_only)
                }
                done_init = True;
        } else {
-               for (i = 0; parm_table[i].label; i++) {
-                       if ((parm_table[i].type == P_STRING ||
-                            parm_table[i].type == P_USTRING) &&
-                           parm_table[i].ptr)
-                       {
-                               string_free((char **)parm_table[i].ptr);
-                       }
-               }
+               free_global_parameters();
        }
 
        memset((void *)&Globals, '\0', sizeof(Globals));
@@ -4805,7 +4846,7 @@ static void init_globals(bool first_time_only)
         * to never expire, though, when this runs out the afs client will 
         * forget the token. Set to 0 to get NEVERDATE.*/
        Globals.iAfsTokenLifetime = 604800;
-       Globals.cups_timeout = CUPS_DEFAULT_TIMEOUT;
+       Globals.cups_connection_timeout = CUPS_DEFAULT_CONNECTION_TIMEOUT;
 
 /* these parameters are set to defaults that are more appropriate
    for the increasing samba install base:
@@ -5247,7 +5288,7 @@ FN_GLOBAL_LIST(lp_svcctl_list, &Globals.szServicesList)
 FN_LOCAL_STRING(lp_cups_options, szCupsOptions)
 FN_GLOBAL_STRING(lp_cups_server, &Globals.szCupsServer)
 FN_GLOBAL_STRING(lp_iprint_server, &Globals.szIPrintServer)
-FN_GLOBAL_INTEGER(lp_cups_timeout, &Globals.cups_timeout)
+FN_GLOBAL_INTEGER(lp_cups_connection_timeout, &Globals.cups_connection_timeout)
 FN_GLOBAL_CONST_STRING(lp_ctdbd_socket, &Globals.ctdbdSocket)
 FN_GLOBAL_LIST(lp_cluster_addresses, &Globals.szClusterAddresses)
 FN_GLOBAL_BOOL(lp_clustering, &Globals.clustering)
@@ -5390,6 +5431,7 @@ static bool do_section(const char *pszSectionName, void *userdata);
 static void init_copymap(struct service *pservice);
 static bool hash_a_service(const char *name, int number);
 static void free_service_byindex(int iService);
+static void free_param_opts(struct param_opt_struct **popts);
 static char * canonicalize_servicename(const char *name);
 static void show_parameter(int parmIndex);
 static bool is_synonym_of(int parm1, int parm2, bool *inverse);
@@ -5644,14 +5686,42 @@ static void init_service(struct service *pservice)
        copy_service(pservice, &sDefault, NULL);
 }
 
+
+/**
+ * free a param_opts structure.
+ * param_opts handling should be moved to talloc;
+ * then this whole functions reduces to a TALLOC_FREE().
+ */
+
+static void free_param_opts(struct param_opt_struct **popts)
+{
+       struct param_opt_struct *opt, *next_opt;
+
+       if (popts == NULL) {
+               return;
+       }
+
+       if (*popts != NULL) {
+               DEBUG(5, ("Freeing parametrics:\n"));
+       }
+       opt = *popts;
+       while (opt != NULL) {
+               string_free(&opt->key);
+               string_free(&opt->value);
+               TALLOC_FREE(opt->list);
+               next_opt = opt->next;
+               SAFE_FREE(opt);
+               opt = next_opt;
+       }
+       *popts = NULL;
+}
+
 /***************************************************************************
  Free the dynamically allocated parts of a service struct.
 ***************************************************************************/
 
 static void free_service(struct service *pservice)
 {
-       int i;
-       struct param_opt_struct *data, *pdata;
        if (!pservice)
                return;
 
@@ -5659,36 +5729,12 @@ static void free_service(struct service *pservice)
                DEBUG(5, ("free_service: Freeing service %s\n",
                       pservice->szService));
 
+       free_parameters(getservicebyname(pservice->szService, NULL));
+
        string_free(&pservice->szService);
        bitmap_free(pservice->copymap);
 
-       for (i = 0; parm_table[i].label; i++) {
-               if ((parm_table[i].type == P_STRING ||
-                    parm_table[i].type == P_USTRING) &&
-                   parm_table[i].p_class == P_LOCAL)
-                       string_free((char **)
-                                   (((char *)pservice) +
-                                    PTR_DIFF(parm_table[i].ptr, &sDefault)));
-               else if (parm_table[i].type == P_LIST &&
-                        parm_table[i].p_class == P_LOCAL)
-                            TALLOC_FREE(*((char ***)
-                                          (((char *)pservice) +
-                                           PTR_DIFF(parm_table[i].ptr,
-                                                    &sDefault))));
-       }
-
-       data = pservice->param_opt;
-       if (data)
-               DEBUG(5,("Freeing parametrics:\n"));
-       while (data) {
-               DEBUG(5,("[%s = %s]\n", data->key, data->value));
-               string_free(&data->key);
-               string_free(&data->value);
-               TALLOC_FREE(data->list);
-               pdata = data->next;
-               SAFE_FREE(data);
-               data = pdata;
-       }
+       free_param_opts(&pservice->param_opt);
 
        ZERO_STRUCTP(pservice);
 }
@@ -5730,7 +5776,6 @@ static int add_a_service(const struct service *pservice, const char *name)
        int i;
        struct service tservice;
        int num_to_alloc = iNumServices + 1;
-       struct param_opt_struct *data, *pdata;
 
        tservice = *pservice;
 
@@ -5740,16 +5785,7 @@ static int add_a_service(const struct service *pservice, const char *name)
                if (i >= 0) {
                        /* Clean all parametric options for service */
                        /* They will be added during parsing again */
-                       data = ServicePtrs[i]->param_opt;
-                       while (data) {
-                               string_free(&data->key);
-                               string_free(&data->value);
-                               TALLOC_FREE(data->list);
-                               pdata = data->next;
-                               SAFE_FREE(data);
-                               data = pdata;
-                       }
-                       ServicePtrs[i]->param_opt = NULL;
+                       free_param_opts(&ServicePtrs[i]->param_opt);
                        return (i);
                }
        }
@@ -6408,13 +6444,51 @@ static int getservicebyname(const char *pszServiceName, struct service *pservice
  If pcopymapDest is NULL then copy all fields
 ***************************************************************************/
 
+/**
+ * Add a parametric option to a param_opt_struct,
+ * replacing old value, if already present.
+ */
+static void set_param_opt(struct param_opt_struct **opt_list,
+                         const char *opt_name,
+                         const char *opt_value)
+{
+       struct param_opt_struct *new_opt, *opt;
+       bool not_added;
+
+       if (opt_list == NULL) {
+               return;
+       }
+
+       opt = *opt_list;
+       not_added = true;
+
+       /* Traverse destination */
+       while (opt) {
+               /* If we already have same option, override it */
+               if (strwicmp(opt->key, opt_name) == 0) {
+                       string_free(&opt->value);
+                       TALLOC_FREE(opt->list);
+                       opt->value = SMB_STRDUP(opt_value);
+                       not_added = false;
+                       break;
+               }
+               opt = opt->next;
+       }
+       if (not_added) {
+           new_opt = SMB_XMALLOC_P(struct param_opt_struct);
+           new_opt->key = SMB_STRDUP(opt_name);
+           new_opt->value = SMB_STRDUP(opt_value);
+           new_opt->list = NULL;
+           DLIST_ADD(*opt_list, new_opt);
+       }
+}
+
 static void copy_service(struct service *pserviceDest, struct service *pserviceSource,
                         struct bitmap *pcopymapDest)
 {
        int i;
        bool bcopyall = (pcopymapDest == NULL);
-       struct param_opt_struct *data, *pdata, *paramo;
-       bool not_added;
+       struct param_opt_struct *data;
 
        for (i = 0; parm_table[i].label; i++)
                if (parm_table[i].ptr && parm_table[i].p_class == P_LOCAL &&
@@ -6472,27 +6546,7 @@ static void copy_service(struct service *pserviceDest, struct service *pserviceS
        
        data = pserviceSource->param_opt;
        while (data) {
-               not_added = True;
-               pdata = pserviceDest->param_opt;
-               /* Traverse destination */
-               while (pdata) {
-                       /* If we already have same option, override it */
-                       if (strwicmp(pdata->key, data->key) == 0) {
-                               string_free(&pdata->value);
-                               TALLOC_FREE(data->list);
-                               pdata->value = SMB_STRDUP(data->value);
-                               not_added = False;
-                               break;
-                       }
-                       pdata = pdata->next;
-               }
-               if (not_added) {
-                   paramo = SMB_XMALLOC_P(struct param_opt_struct);
-                   paramo->key = SMB_STRDUP(data->key);
-                   paramo->value = SMB_STRDUP(data->value);
-                   paramo->list = NULL;
-                   DLIST_ADD(pserviceDest->param_opt, paramo);
-               }
+               set_param_opt(&pserviceDest->param_opt, data->key, data->value);
                data = data->next;
        }
 }
@@ -6560,7 +6614,7 @@ static struct smbconf_ctx *lp_smbconf_ctx(void)
        return conf_ctx;
 }
 
-static bool process_registry_service(struct smbconf_service *service)
+static bool process_smbconf_service(struct smbconf_service *service)
 {
        uint32_t count;
        bool ret;
@@ -6616,7 +6670,7 @@ static bool process_registry_globals(void)
                goto done;
        }
 
-       ret = process_registry_service(service);
+       ret = process_smbconf_service(service);
        if (!ret) {
                goto done;
        }
@@ -6654,7 +6708,7 @@ static bool process_registry_shares(void)
                if (strequal(service[count]->name, GLOBAL_NAME)) {
                        continue;
                }
-               ret = process_registry_service(service[count]);
+               ret = process_smbconf_service(service[count]);
                if (!ret) {
                        goto done;
                }
@@ -7157,14 +7211,11 @@ bool lp_do_parameter(int snum, const char *pszParmName, const char *pszParmValue
        int parmnum, i;
        void *parm_ptr = NULL;  /* where we are going to store the result */
        void *def_ptr = NULL;
-       struct param_opt_struct *paramo, *data;
-       bool not_added;
+       struct param_opt_struct **opt_list;
 
        parmnum = map_parameter(pszParmName);
 
        if (parmnum < 0) {
-               TALLOC_CTX *frame;
-
                if (strchr(pszParmName, ':') == NULL) {
                        DEBUG(0, ("Ignoring unknown parameter \"%s\"\n",
                                  pszParmName));
@@ -7175,37 +7226,10 @@ bool lp_do_parameter(int snum, const char *pszParmName, const char *pszParmValue
                 * We've got a parametric option
                 */
 
-               frame = talloc_stackframe();
+               opt_list = (snum < 0)
+                       ? &Globals.param_opt : &ServicePtrs[snum]->param_opt;
+               set_param_opt(opt_list, pszParmName, pszParmValue);
 
-               not_added = True;
-               data = (snum < 0)
-                       ? Globals.param_opt : ServicePtrs[snum]->param_opt;
-               /* Traverse destination */
-               while (data) {
-                       /* If we already have same option, override it */
-                       if (strwicmp(data->key, pszParmName) == 0) {
-                               string_free(&data->value);
-                               TALLOC_FREE(data->list);
-                               data->value = SMB_STRDUP(pszParmValue);
-                               not_added = False;
-                               break;
-                       }
-                       data = data->next;
-               }
-               if (not_added) {
-                       paramo = SMB_XMALLOC_P(struct param_opt_struct);
-                       paramo->key = SMB_STRDUP(pszParmName);
-                       paramo->value = SMB_STRDUP(pszParmValue);
-                       paramo->list = NULL;
-                       if (snum < 0) {
-                               DLIST_ADD(Globals.param_opt, paramo);
-                       } else {
-                               DLIST_ADD(ServicePtrs[snum]->param_opt,
-                                         paramo);
-                       }
-               }
-
-               TALLOC_FREE(frame);
                return (True);
        }
 
@@ -7226,9 +7250,7 @@ bool lp_do_parameter(int snum, const char *pszParmName, const char *pszParmValue
                               pszParmName));
                        return (True);
                }
-               parm_ptr =
-                       ((char *)ServicePtrs[snum]) + PTR_DIFF(def_ptr,
-                                                           &sDefault);
+               parm_ptr = lp_local_ptr(snum, def_ptr);
        }
 
        if (snum >= 0) {
@@ -7826,7 +7848,7 @@ static void lp_add_auto_services(char *str)
  Auto-load one printer.
 ***************************************************************************/
 
-void lp_add_one_printer(char *name, char *comment)
+void lp_add_one_printer(const char *name, const char *comment, void *pdata)
 {
        int printers = lp_servicenumber(PRINTERS_NAME);
        int i;
@@ -8734,17 +8756,7 @@ void gfree_loadparm(void)
        /* Now release all resources allocated to global
           parameters and the default service */
 
-       for (i = 0; parm_table[i].label; i++) 
-       {
-               if ( parm_table[i].type == P_STRING 
-                       || parm_table[i].type == P_USTRING ) 
-               {
-                       string_free( (char**)parm_table[i].ptr );
-               }
-               else if (parm_table[i].type == P_LIST) {
-                       TALLOC_FREE( *((char***)parm_table[i].ptr) );
-               }
-       }
+       free_global_parameters();
 }
 
 
@@ -8765,9 +8777,6 @@ bool lp_is_in_client(void)
     return in_client;
 }
 
-
-
-
 /***************************************************************************
  Load the services array from the services file. Return True on success, 
  False on failure.
@@ -8783,7 +8792,6 @@ bool lp_load_ex(const char *pszFname,
 {
        char *n2 = NULL;
        bool bRetval;
-       struct param_opt_struct *data, *pdata;
 
        bRetval = False;
 
@@ -8801,22 +8809,11 @@ bool lp_load_ex(const char *pszFname,
                lp_save_defaults();
        }
 
+       free_param_opts(&Globals.param_opt);
+
        /* We get sections first, so have to start 'behind' to make up */
        iServiceIndex = -1;
 
-       if (Globals.param_opt != NULL) {
-               data = Globals.param_opt;
-               while (data) {
-                       string_free(&data->key);
-                       string_free(&data->value);
-                       TALLOC_FREE(data->list);
-                       pdata = data->next;
-                       SAFE_FREE(data);
-                       data = pdata;
-               }
-               Globals.param_opt = NULL;
-       }
-
        if (lp_config_backend_is_file()) {
                n2 = alloc_sub_basic(get_current_username(),
                                        current_user_info.domain,
diff --git a/source3/param/test_lp_load.c b/source3/param/test_lp_load.c
new file mode 100644 (file)
index 0000000..db1bad4
--- /dev/null
@@ -0,0 +1,88 @@
+/*
+ * Unix SMB/CIFS implementation.
+ * Test for lp_load()
+ * Copyright (C) Michael Adam 2008
+ *
+ * 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"
+
+extern bool AllowDebugChange;
+
+int main(int argc, const char **argv)
+{
+       const char *config_file = get_dyn_CONFIGFILE();
+       int ret = 0;
+       poptContext pc;
+       char *count_str = NULL;
+       int i, count = 1;
+
+       struct poptOption long_options[] = {
+               POPT_AUTOHELP
+               {"count", 'c', POPT_ARG_STRING, &count_str, 1,
+                "Load config <count> number of times"},
+               POPT_COMMON_DEBUGLEVEL
+               POPT_TABLEEND
+       };
+
+       TALLOC_CTX *frame = talloc_stackframe();
+
+       load_case_tables();
+       DEBUGLEVEL_CLASS[DBGC_ALL] = 0;
+
+       pc = poptGetContext(NULL, argc, argv, long_options,
+                           POPT_CONTEXT_KEEP_FIRST);
+       poptSetOtherOptionHelp(pc, "[OPTION...] <config-file>");
+
+       while(poptGetNextOpt(pc) != -1);
+
+       setup_logging(poptGetArg(pc), True);
+
+       if (poptPeekArg(pc)) {
+               config_file = poptGetArg(pc);
+       }
+
+       poptFreeContext(pc);
+
+       if (count_str != NULL) {
+               count = atoi(count_str);
+       }
+
+       dbf = x_stderr;
+       /* Don't let the debuglevel be changed by smb.conf. */
+       AllowDebugChange = False;
+
+       for (i=0; i < count; i++) {
+               printf("call lp_load() #%d: ", i+1);
+               if (!lp_load_with_registry_shares(config_file,
+                                                 False, /* global only */
+                                                 True,  /* save defaults */
+                                                 False, /*add_ipc */
+                                                 True)) /*init globals */
+               {
+                       printf("ERROR.\n");
+                       ret = 1;
+                       goto done;
+               }
+               printf("ok.\n");
+       }
+
+
+done:
+       TALLOC_FREE(frame);
+       gfree_loadparm();
+       return ret;
+}
+
index 4527ae712766e47fb0a719450d312e15e573c7bd..306d4d0a35c5ce5cb4477c78973ff35a341604dc 100644 (file)
@@ -259,6 +259,31 @@ bool secrets_fetch_domain_guid(const char *domain, struct GUID *guid)
        return True;
 }
 
+bool secrets_store_local_schannel_key(uint8_t schannel_key[16])
+{
+       return secrets_store(SECRETS_LOCAL_SCHANNEL_KEY, schannel_key, 16);
+}
+
+bool secrets_fetch_local_schannel_key(uint8_t schannel_key[16])
+{
+       size_t size = 0;
+       uint8_t *key;
+
+       key = (uint8_t *)secrets_fetch(SECRETS_LOCAL_SCHANNEL_KEY, &size);
+       if (key == NULL) {
+               return false;
+       }
+
+       if (size != 16) {
+               SAFE_FREE(key);
+               return false;
+       }
+
+       memcpy(schannel_key, key, 16);
+       SAFE_FREE(key);
+       return true;
+}
+
 /**
  * Form a key for fetching the machine trust account sec channel type
  *
index 23144d5a9550dc9e6ba2bea5eaf94d6bccaf4427..fc21f271bd9aa2aaba391edcbeaf31e76d27cbf1 100644 (file)
@@ -60,5 +60,5 @@ void load_printers(void)
 
        /* load all printcap printers */
        if (lp_load_printers() && lp_servicenumber(PRINTERS_NAME) >= 0)
-               pcap_printer_fn(lp_add_one_printer);
+               pcap_printer_fn(lp_add_one_printer, NULL);
 }
index 23df17c3896ab97a017700c07ef19b5707229fa0..f6599c413d042bb159f76bed503c0abe9f61a26b 100644 (file)
@@ -34,6 +34,7 @@ static struct notify_queue {
        size_t buflen;
 } *notify_queue_head = NULL;
 
+static struct timed_event *notify_event;
 
 static bool create_send_ctx(void)
 {
@@ -214,6 +215,22 @@ void print_notify_send_messages(struct messaging_context *msg_ctx,
        num_messages = 0;
 }
 
+/*******************************************************************
+ Event handler to send the messages.
+*******************************************************************/
+
+static void print_notify_event_send_messages(struct event_context *event_ctx,
+                                       struct timed_event *te,
+                                       const struct timeval *now,
+                                       void *private_data)
+{
+       /* Remove this timed event handler. */
+       TALLOC_FREE(notify_event);
+
+       change_to_root_user();
+       print_notify_send_messages(smbd_messaging_context(), 0);
+}
+
 /**********************************************************************
  deep copy a SPOOLSS_NOTIFY_MSG structure using a TALLOC_CTX
  *********************************************************************/
@@ -304,6 +321,15 @@ to notify_queue_head\n", msg->type, msg->field, msg->printer));
 
        DLIST_ADD_END(notify_queue_head, pnqueue, struct notify_queue *);
        num_messages++;
+
+       if (smbd_event_context()) {
+               /* Add an event for 1 second's time to send this queue. */
+               notify_event = event_add_timed(smbd_event_context(), NULL,
+                                       timeval_current_ofs(1,0),
+                                       "print_notify",
+                                       print_notify_event_send_messages, NULL);
+       }
+
 }
 
 static void send_notify_field_values(const char *sharename, uint32 type,
index ded985c260d5af5bc28a044d0d4c600e740bfbf4..850375e82b300a6e0a205fb42fafdc24425206fe 100644 (file)
@@ -1377,6 +1377,7 @@ static int file_version_is_newer(connection_struct *conn, fstring new_file, fstr
                }
        }
        close_file(fsp, NORMAL_CLOSE);
+       fsp = NULL;
 
        /* Get file version info (if available) for new file */
        filepath = driver_unix_convert(conn,new_file,&stat_buf);
@@ -1417,6 +1418,7 @@ static int file_version_is_newer(connection_struct *conn, fstring new_file, fstr
                }
        }
        close_file(fsp, NORMAL_CLOSE);
+       fsp = NULL;
 
        if (use_version && (new_major != old_major || new_minor != old_minor)) {
                /* Compare versions and choose the larger version number */
@@ -5491,7 +5493,7 @@ static SEC_DESC_BUF *construct_default_printer_sdb(TALLOC_CTX *ctx)
 {
        SEC_ACE ace[5]; /* max number of ace entries */
        int i = 0;
-       SEC_ACCESS sa;
+       uint32_t sa;
        SEC_ACL *psa = NULL;
        SEC_DESC_BUF *sdb = NULL;
        SEC_DESC *psd = NULL;
@@ -5500,7 +5502,7 @@ static SEC_DESC_BUF *construct_default_printer_sdb(TALLOC_CTX *ctx)
 
        /* Create an ACE where Everyone is allowed to print */
 
-       init_sec_access(&sa, PRINTER_ACE_PRINT);
+       sa = PRINTER_ACE_PRINT;
        init_sec_ace(&ace[i++], &global_sid_World, SEC_ACE_TYPE_ACCESS_ALLOWED,
                     sa, SEC_ACE_FLAG_CONTAINER_INHERIT);
 
@@ -5512,7 +5514,7 @@ static SEC_DESC_BUF *construct_default_printer_sdb(TALLOC_CTX *ctx)
                sid_copy(&domadmins_sid, get_global_sam_sid());
                sid_append_rid(&domadmins_sid, DOMAIN_GROUP_RID_ADMINS);
                
-               init_sec_access(&sa, PRINTER_ACE_FULL_CONTROL);
+               sa = PRINTER_ACE_FULL_CONTROL;
                init_sec_ace(&ace[i++], &domadmins_sid, 
                        SEC_ACE_TYPE_ACCESS_ALLOWED, sa, 
                        SEC_ACE_FLAG_OBJECT_INHERIT | SEC_ACE_FLAG_INHERIT_ONLY);
@@ -5522,7 +5524,7 @@ static SEC_DESC_BUF *construct_default_printer_sdb(TALLOC_CTX *ctx)
        else if (secrets_fetch_domain_sid(lp_workgroup(), &adm_sid)) {
                sid_append_rid(&adm_sid, DOMAIN_USER_RID_ADMIN);
 
-               init_sec_access(&sa, PRINTER_ACE_FULL_CONTROL);
+               sa = PRINTER_ACE_FULL_CONTROL;
                init_sec_ace(&ace[i++], &adm_sid, 
                        SEC_ACE_TYPE_ACCESS_ALLOWED, sa, 
                        SEC_ACE_FLAG_OBJECT_INHERIT | SEC_ACE_FLAG_INHERIT_ONLY);
@@ -5532,7 +5534,7 @@ static SEC_DESC_BUF *construct_default_printer_sdb(TALLOC_CTX *ctx)
 
        /* add BUILTIN\Administrators as FULL CONTROL */
 
-       init_sec_access(&sa, PRINTER_ACE_FULL_CONTROL);
+       sa = PRINTER_ACE_FULL_CONTROL;
        init_sec_ace(&ace[i++], &global_sid_Builtin_Administrators, 
                SEC_ACE_TYPE_ACCESS_ALLOWED, sa, 
                SEC_ACE_FLAG_OBJECT_INHERIT | SEC_ACE_FLAG_INHERIT_ONLY);
index 30cb254a29a1805925f8ff531148a2893500af2d..10c1a2d608bf8df9ea8173440b11707ef2b3a258 100644 (file)
 #include "includes.h"
 
 
-typedef struct pcap_cache {
+struct pcap_cache {
        char *name;
        char *comment;
        struct pcap_cache *next;
-} pcap_cache_t;
+};
 
-static pcap_cache_t *pcap_cache = NULL;
+/* The systemwide printcap cache. */
+static struct pcap_cache *pcap_cache = NULL;
 
-bool pcap_cache_add(const char *name, const char *comment)
+bool pcap_cache_add_specific(struct pcap_cache **ppcache, const char *name, const char *comment)
 {
-       pcap_cache_t *p;
+       struct pcap_cache *p;
 
-       if (name == NULL || ((p = SMB_MALLOC_P(pcap_cache_t)) == NULL))
-               return False;
+       if (name == NULL || ((p = SMB_MALLOC_P(struct pcap_cache)) == NULL))
+               return false;
 
        p->name = SMB_STRDUP(name);
        p->comment = (comment && *comment) ? SMB_STRDUP(comment) : NULL;
 
-       p->next = pcap_cache;
-       pcap_cache = p;
+       DEBUG(11,("pcap_cache_add_specific: Adding name %s info %s\n",
+               p->name, p->comment ? p->comment : ""));
+
+       p->next = *ppcache;
+       *ppcache = p;
 
-       return True;
+       return true;
 }
 
-static void pcap_cache_destroy(pcap_cache_t *cache)
+void pcap_cache_destroy_specific(struct pcap_cache **pp_cache)
 {
-       pcap_cache_t *p, *next;
+       struct pcap_cache *p, *next;
 
-       for (p = cache; p != NULL; p = next) {
+       for (p = *pp_cache; p != NULL; p = next) {
                next = p->next;
 
                SAFE_FREE(p->name);
                SAFE_FREE(p->comment);
                SAFE_FREE(p);
        }
+       *pp_cache = NULL;
+}
+
+bool pcap_cache_add(const char *name, const char *comment)
+{
+       return pcap_cache_add_specific(&pcap_cache, name, comment);
 }
 
 bool pcap_cache_loaded(void)
@@ -105,11 +115,21 @@ bool pcap_cache_loaded(void)
        return (pcap_cache != NULL);
 }
 
+void pcap_cache_replace(const struct pcap_cache *pcache)
+{
+       const struct pcap_cache *p;
+
+       pcap_cache_destroy_specific(&pcap_cache);
+       for (p = pcache; p; p = p->next) {
+               pcap_cache_add(p->name, p->comment);
+       }
+}
+
 void pcap_cache_reload(void)
 {
        const char *pcap_name = lp_printcapname();
        bool pcap_reloaded = False;
-       pcap_cache_t *tmp_cache = NULL;
+       struct pcap_cache *tmp_cache = NULL;
        XFILE *pcap_file;
        char *pcap_line;
 
@@ -223,9 +243,9 @@ done:
        DEBUG(3, ("reload status: %s\n", (pcap_reloaded) ? "ok" : "error"));
 
        if (pcap_reloaded)
-               pcap_cache_destroy(tmp_cache);
+               pcap_cache_destroy_specific(&tmp_cache);
        else {
-               pcap_cache_destroy(pcap_cache);
+               pcap_cache_destroy_specific(&pcap_cache);
                pcap_cache = tmp_cache;
        }
 
@@ -235,7 +255,7 @@ done:
 
 bool pcap_printername_ok(const char *printername)
 {
-       pcap_cache_t *p;
+       struct pcap_cache *p;
 
        for (p = pcap_cache; p != NULL; p = p->next)
                if (strequal(p->name, printername))
@@ -245,19 +265,22 @@ bool pcap_printername_ok(const char *printername)
 }
 
 /***************************************************************************
-run a function on each printer name in the printcap file. The function is 
-passed the primary name and the comment (if possible). Note the fn() takes
-strings in DOS codepage. This means the xxx_printer_fn() calls must be fixed
-to return DOS codepage. FIXME !! JRA.
-
-XXX: I'm not sure if this comment still applies.. Anyone?  -Rob
+run a function on each printer name in the printcap file.
 ***************************************************************************/
-void pcap_printer_fn(void (*fn)(char *, char *))
+
+void pcap_printer_fn_specific(const struct pcap_cache *pc,
+                       void (*fn)(const char *, const char *, void *),
+                       void *pdata)
 {
-       pcap_cache_t *p;
+       const struct pcap_cache *p;
 
-       for (p = pcap_cache; p != NULL; p = p->next)
-               fn(p->name, p->comment);
+       for (p = pc; p != NULL; p = p->next)
+               fn(p->name, p->comment, pdata);
 
        return;
 }
+
+void pcap_printer_fn(void (*fn)(const char *, const char *, void *), void *pdata)
+{
+       return pcap_printer_fn_specific(pcap_cache, fn, pdata);
+}
index 2b2cf159fb41a8ab541bab92a81b6f71cfc6aafe..ca3415ca5a0cfec652091eb64425e9364016c11e 100644 (file)
@@ -2,21 +2,26 @@
  * Support code for the Common UNIX Printing System ("CUPS")
  *
  * Copyright 1999-2003 by Michael R Sweet.
+ * Copyright 2008 Jeremy Allison.
  *
  * 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/>.
  */
 
+/*
+ * JRA. Converted to utf8 pull/push.
+ */
+
 #include "includes.h"
 #include "printing.h"
 
@@ -51,24 +56,23 @@ cups_passwd_cb(const char *prompt)  /* I - Prompt */
        return (NULL);
 }
 
-static http_t *cups_connect(void)
+static http_t *cups_connect(TALLOC_CTX *frame)
 {
-       http_t *http;
-       char *server, *p;
+       http_t *http = NULL;
+       char *server = NULL, *p = NULL;
        int port;
-       int timeout = lp_cups_timeout();
-
-       gotalarm = 0;
-
-       if (timeout) {
-                CatchSignal(SIGALRM, SIGNAL_CAST gotalarm_sig);
-                alarm(timeout);
-        }
+       int timeout = lp_cups_connection_timeout();
+       size_t size;
 
        if (lp_cups_server() != NULL && strlen(lp_cups_server()) > 0) {
-               server = smb_xstrdup(lp_cups_server());
+               if (!push_utf8_talloc(frame, &server, lp_cups_server(), &size)) {
+                       return NULL;
+               }
        } else {
-               server = smb_xstrdup(cupsServer());
+               server = talloc_strdup(frame,cupsServer());
+       }
+       if (!server) {
+               return NULL;
        }
 
        p = strchr(server, ':');
@@ -82,6 +86,13 @@ static http_t *cups_connect(void)
        DEBUG(10, ("connecting to cups server %s:%d\n",
                   server, port));
 
+       gotalarm = 0;
+
+       if (timeout) {
+                CatchSignal(SIGALRM, SIGNAL_CAST gotalarm_sig);
+                alarm(timeout);
+        }
+
        http = httpConnect(server, port);
 
        CatchSignal(SIGALRM, SIGNAL_CAST SIG_IGN);
@@ -92,12 +103,49 @@ static http_t *cups_connect(void)
                         server, port, strerror(errno)));
        }
 
-       SAFE_FREE(server);
        return http;
 }
 
-bool cups_cache_reload(void)
+static void send_pcap_info(const char *name, const char *info, void *pd)
 {
+       int fd = *(int *)pd;
+       size_t namelen = name ? strlen(name)+1 : 0;
+       size_t infolen = info ? strlen(info)+1 : 0;
+
+       DEBUG(11,("send_pcap_info: writing namelen %u\n", (unsigned int)namelen));
+       if (sys_write(fd, &namelen, sizeof(namelen)) != sizeof(namelen)) {
+               DEBUG(10,("send_pcap_info: namelen write failed %s\n",
+                       strerror(errno)));
+               return;
+       }
+       DEBUG(11,("send_pcap_info: writing infolen %u\n", (unsigned int)infolen));
+       if (sys_write(fd, &infolen, sizeof(infolen)) != sizeof(infolen)) {
+               DEBUG(10,("send_pcap_info: infolen write failed %s\n",
+                       strerror(errno)));
+               return;
+       }
+       if (namelen) {
+               DEBUG(11,("send_pcap_info: writing name %s\n", name));
+               if (sys_write(fd, name, namelen) != namelen) {
+                       DEBUG(10,("send_pcap_info: name write failed %s\n",
+                               strerror(errno)));
+                       return;
+               }
+       }
+       if (infolen) {
+               DEBUG(11,("send_pcap_info: writing info %s\n", info));
+               if (sys_write(fd, info, infolen) != infolen) {
+                       DEBUG(10,("send_pcap_info: info write failed %s\n",
+                               strerror(errno)));
+                       return;
+               }
+       }
+}
+
+static bool cups_cache_reload_async(int fd)
+{
+       TALLOC_CTX *frame = talloc_stackframe();
+       struct pcap_cache *tmp_pcap_cache = NULL;
        http_t          *http = NULL;           /* HTTP connection to server */
        ipp_t           *request = NULL,        /* IPP Request */
                        *response = NULL;       /* IPP Response */
@@ -109,8 +157,9 @@ bool cups_cache_reload(void)
                        {
                          "printer-name",
                          "printer-info"
-                       };       
+                       };
        bool ret = False;
+       size_t size;
 
        DEBUG(5, ("reloading cups printcap cache\n"));
 
@@ -124,7 +173,7 @@ bool cups_cache_reload(void)
        * Try to connect to the server...
        */
 
-       if ((http = cups_connect()) == NULL) {
+       if ((http = cups_connect(frame)) == NULL) {
                goto out;
        }
 
@@ -145,7 +194,7 @@ bool cups_cache_reload(void)
        language = cupsLangDefault();
 
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_CHARSET,
-                     "attributes-charset", NULL, cupsLangEncoding(language));
+                     "attributes-charset", NULL, "utf-8");
 
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE,
                      "attributes-natural-language", NULL, language->language);
@@ -185,12 +234,24 @@ bool cups_cache_reload(void)
 
                while (attr != NULL && attr->group_tag == IPP_TAG_PRINTER) {
                        if (strcmp(attr->name, "printer-name") == 0 &&
-                           attr->value_tag == IPP_TAG_NAME)
-                               name = attr->values[0].string.text;
+                           attr->value_tag == IPP_TAG_NAME) {
+                               if (!pull_utf8_talloc(frame,
+                                               &name,
+                                               attr->values[0].string.text,
+                                               &size)) {
+                                       goto out;
+                               }
+                       }
 
                        if (strcmp(attr->name, "printer-info") == 0 &&
-                           attr->value_tag == IPP_TAG_TEXT)
-                               info = attr->values[0].string.text;
+                           attr->value_tag == IPP_TAG_TEXT) {
+                               if (!pull_utf8_talloc(frame,
+                                               &info,
+                                               attr->values[0].string.text,
+                                               &size)) {
+                                       goto out;
+                               }
+                       }
 
                        attr = attr->next;
                }
@@ -202,7 +263,7 @@ bool cups_cache_reload(void)
                if (name == NULL)
                        break;
 
-               if (!pcap_cache_add(name, info)) {
+               if (!pcap_cache_add_specific(&tmp_pcap_cache, name, info)) {
                        goto out;
                }
        }
@@ -225,7 +286,7 @@ bool cups_cache_reload(void)
        request->request.op.request_id   = 1;
 
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_CHARSET,
-                     "attributes-charset", NULL, cupsLangEncoding(language));
+                     "attributes-charset", NULL, "utf-8");
 
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE,
                      "attributes-natural-language", NULL, language->language);
@@ -265,12 +326,24 @@ bool cups_cache_reload(void)
 
                while (attr != NULL && attr->group_tag == IPP_TAG_PRINTER) {
                        if (strcmp(attr->name, "printer-name") == 0 &&
-                           attr->value_tag == IPP_TAG_NAME)
-                               name = attr->values[0].string.text;
+                           attr->value_tag == IPP_TAG_NAME) {
+                               if (!pull_utf8_talloc(frame,
+                                               &name,
+                                               attr->values[0].string.text,
+                                               &size)) {
+                                       goto out;
+                               }
+                       }
 
                        if (strcmp(attr->name, "printer-info") == 0 &&
-                           attr->value_tag == IPP_TAG_TEXT)
-                               info = attr->values[0].string.text;
+                           attr->value_tag == IPP_TAG_TEXT) {
+                               if (!pull_utf8_talloc(frame,
+                                               &info,
+                                               attr->values[0].string.text,
+                                               &size)) {
+                                       goto out;
+                               }
+                       }
 
                        attr = attr->next;
                }
@@ -282,7 +355,7 @@ bool cups_cache_reload(void)
                if (name == NULL)
                        break;
 
-               if (!pcap_cache_add(name, info)) {
+               if (!pcap_cache_add_specific(&tmp_pcap_cache, name, info)) {
                        goto out;
                }
        }
@@ -299,9 +372,229 @@ bool cups_cache_reload(void)
        if (http)
                httpClose(http);
 
+       /* Send all the entries up the pipe. */
+       if (tmp_pcap_cache) {
+               pcap_printer_fn_specific(tmp_pcap_cache,
+                               send_pcap_info,
+                               (void *)&fd);
+
+               pcap_cache_destroy_specific(&tmp_pcap_cache);
+       }
+       TALLOC_FREE(frame);
        return ret;
 }
 
+static struct pcap_cache *local_pcap_copy;
+struct fd_event *cache_fd_event;
+
+static bool cups_pcap_load_async(int *pfd)
+{
+       int fds[2];
+       pid_t pid;
+
+       *pfd = -1;
+
+       if (cache_fd_event) {
+               DEBUG(3,("cups_pcap_load_async: already waiting for "
+                       "a refresh event\n" ));
+               return false;
+       }
+
+       DEBUG(5,("cups_pcap_load_async: asynchronously loading cups printers\n"));
+
+       if (pipe(fds) == -1) {
+               return false;
+       }
+
+       pid = sys_fork();
+       if (pid == (pid_t)-1) {
+               DEBUG(10,("cups_pcap_load_async: fork failed %s\n",
+                       strerror(errno) ));
+               close(fds[0]);
+               close(fds[1]);
+               return false;
+       }
+
+       if (pid) {
+               DEBUG(10,("cups_pcap_load_async: child pid = %u\n",
+                       (unsigned int)pid ));
+               /* Parent. */
+               close(fds[1]);
+               *pfd = fds[0];
+               return true;
+       }
+
+       /* Child. */
+       if (!reinit_after_fork(smbd_messaging_context(), true)) {
+               DEBUG(0,("cups_pcap_load_async: reinit_after_fork() failed\n"));
+               smb_panic("cups_pcap_load_async: reinit_after_fork() failed");
+       }
+
+       close(fds[0]);
+       cups_cache_reload_async(fds[1]);
+       close(fds[1]);
+       _exit(0);
+}
+
+static void cups_async_callback(struct event_context *event_ctx,
+                               struct fd_event *event,
+                               uint16 flags,
+                               void *p)
+{
+       TALLOC_CTX *frame = talloc_stackframe();
+       int fd = *(int *)p;
+       struct pcap_cache *tmp_pcap_cache = NULL;
+
+       DEBUG(5,("cups_async_callback: callback received for printer data. "
+               "fd = %d\n", fd));
+
+       while (1) {
+               char *name = NULL, *info = NULL;
+               size_t namelen = 0, infolen = 0;
+               ssize_t ret = -1;
+
+               ret = sys_read(fd, &namelen, sizeof(namelen));
+               if (ret == 0) {
+                       /* EOF */
+                       break;
+               }
+               if (ret != sizeof(namelen)) {
+                       DEBUG(10,("cups_async_callback: namelen read failed %d %s\n",
+                               errno, strerror(errno)));
+                       break;
+               }
+
+               DEBUG(11,("cups_async_callback: read namelen %u\n",
+                       (unsigned int)namelen));
+
+               ret = sys_read(fd, &infolen, sizeof(infolen));
+               if (ret == 0) {
+                       /* EOF */
+                       break;
+               }
+               if (ret != sizeof(infolen)) {
+                       DEBUG(10,("cups_async_callback: infolen read failed %s\n",
+                               strerror(errno)));
+                       break;
+               }
+
+               DEBUG(11,("cups_async_callback: read infolen %u\n",
+                       (unsigned int)infolen));
+
+               if (namelen) {
+                       name = TALLOC_ARRAY(frame, char, namelen);
+                       if (!name) {
+                               break;
+                       }
+                       ret = sys_read(fd, name, namelen);
+                       if (ret == 0) {
+                               /* EOF */
+                               break;
+                       }
+                       if (ret != namelen) {
+                               DEBUG(10,("cups_async_callback: name read failed %s\n",
+                                       strerror(errno)));
+                               break;
+                       }
+                       DEBUG(11,("cups_async_callback: read name %s\n",
+                               name));
+               } else {
+                       name = NULL;
+               }
+               if (infolen) {
+                       info = TALLOC_ARRAY(frame, char, infolen);
+                       if (!info) {
+                               break;
+                       }
+                       ret = sys_read(fd, info, infolen);
+                       if (ret == 0) {
+                               /* EOF */
+                               break;
+                       }
+                       if (ret != infolen) {
+                               DEBUG(10,("cups_async_callback: info read failed %s\n",
+                                       strerror(errno)));
+                               break;
+                       }
+                       DEBUG(11,("cups_async_callback: read info %s\n",
+                               info));
+               } else {
+                       info = NULL;
+               }
+
+               /* Add to our local pcap cache. */
+               pcap_cache_add_specific(&tmp_pcap_cache, name, info);
+               TALLOC_FREE(name);
+               TALLOC_FREE(info);
+       }
+
+       TALLOC_FREE(frame);
+       if (tmp_pcap_cache) {
+               /* We got a namelist, replace our local cache. */
+               pcap_cache_destroy_specific(&local_pcap_copy);
+               local_pcap_copy = tmp_pcap_cache;
+
+               /* And the systemwide pcap cache. */
+               pcap_cache_replace(local_pcap_copy);
+       } else {
+               DEBUG(2,("cups_async_callback: failed to read a new "
+                       "printer list\n"));
+       }
+       close(fd);
+       TALLOC_FREE(p);
+       TALLOC_FREE(cache_fd_event);
+}
+
+bool cups_cache_reload(void)
+{
+       int *p_pipe_fd = TALLOC_P(NULL, int);
+
+       if (!p_pipe_fd) {
+               return false;
+       }
+
+       *p_pipe_fd = -1;
+
+       /* Set up an async refresh. */
+       if (!cups_pcap_load_async(p_pipe_fd)) {
+               return false;
+       }
+       if (!local_pcap_copy) {
+               /* We have no local cache, wait directly for
+                * async refresh to complete.
+                */
+               DEBUG(10,("cups_cache_reload: sync read on fd %d\n",
+                       *p_pipe_fd ));
+
+               cups_async_callback(smbd_event_context(),
+                                       NULL,
+                                       EVENT_FD_READ,
+                                       (void *)p_pipe_fd);
+               if (!local_pcap_copy) {
+                       return false;
+               }
+       } else {
+               /* Replace the system cache with our
+                * local copy. */
+               pcap_cache_replace(local_pcap_copy);
+
+               DEBUG(10,("cups_cache_reload: async read on fd %d\n",
+                       *p_pipe_fd ));
+
+               /* Trigger an event when the pipe can be read. */
+               cache_fd_event = event_add_fd(smbd_event_context(),
+                                       NULL, *p_pipe_fd,
+                                       EVENT_FD_READ,
+                                       cups_async_callback,
+                                       (void *)p_pipe_fd);
+               if (!cache_fd_event) {
+                       close(*p_pipe_fd);
+                       TALLOC_FREE(p_pipe_fd);
+                       return false;
+               }
+       }
+       return true;
+}
 
 /*
  * 'cups_job_delete()' - Delete a job.
@@ -309,13 +602,15 @@ bool cups_cache_reload(void)
 
 static int cups_job_delete(const char *sharename, const char *lprm_command, struct printjob *pjob)
 {
+       TALLOC_CTX *frame = talloc_stackframe();
        int             ret = 1;                /* Return value */
        http_t          *http = NULL;           /* HTTP connection to server */
        ipp_t           *request = NULL,        /* IPP Request */
                        *response = NULL;       /* IPP Response */
        cups_lang_t     *language = NULL;       /* Default language */
+       char *user = NULL;
        char            uri[HTTP_MAX_URI]; /* printer-uri attribute */
-
+       size_t size;
 
        DEBUG(5,("cups_job_delete(%s, %p (%d))\n", sharename, pjob, pjob->sysjob));
 
@@ -329,7 +624,7 @@ static int cups_job_delete(const char *sharename, const char *lprm_command, stru
        * Try to connect to the server...
        */
 
-       if ((http = cups_connect()) == NULL) {
+       if ((http = cups_connect(frame)) == NULL) {
                goto out;
        }
 
@@ -351,7 +646,7 @@ static int cups_job_delete(const char *sharename, const char *lprm_command, stru
        language = cupsLangDefault();
 
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_CHARSET,
-                    "attributes-charset", NULL, cupsLangEncoding(language));
+                     "attributes-charset", NULL, "utf-8");
 
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE,
                     "attributes-natural-language", NULL, language->language);
@@ -360,8 +655,12 @@ static int cups_job_delete(const char *sharename, const char *lprm_command, stru
 
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "job-uri", NULL, uri);
 
+       if (!push_utf8_talloc(frame, &user, pjob->user, &size)) {
+               goto out;
+       }
+
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name",
-                    NULL, pjob->user);
+                    NULL, user);
 
        /*
        * Do the request and get back a response...
@@ -389,6 +688,7 @@ static int cups_job_delete(const char *sharename, const char *lprm_command, stru
        if (http)
                httpClose(http);
 
+       TALLOC_FREE(frame);
        return ret;
 }
 
@@ -399,13 +699,15 @@ static int cups_job_delete(const char *sharename, const char *lprm_command, stru
 
 static int cups_job_pause(int snum, struct printjob *pjob)
 {
+       TALLOC_CTX *frame = talloc_stackframe();
        int             ret = 1;                /* Return value */
        http_t          *http = NULL;           /* HTTP connection to server */
        ipp_t           *request = NULL,        /* IPP Request */
                        *response = NULL;       /* IPP Response */
        cups_lang_t     *language = NULL;       /* Default language */
+       char *user = NULL;
        char            uri[HTTP_MAX_URI]; /* printer-uri attribute */
-
+       size_t size;
 
        DEBUG(5,("cups_job_pause(%d, %p (%d))\n", snum, pjob, pjob->sysjob));
 
@@ -419,7 +721,7 @@ static int cups_job_pause(int snum, struct printjob *pjob)
        * Try to connect to the server...
        */
 
-       if ((http = cups_connect()) == NULL) {
+       if ((http = cups_connect(frame)) == NULL) {
                goto out;
        }
 
@@ -441,7 +743,7 @@ static int cups_job_pause(int snum, struct printjob *pjob)
        language = cupsLangDefault();
 
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_CHARSET,
-                    "attributes-charset", NULL, cupsLangEncoding(language));
+                     "attributes-charset", NULL, "utf-8");
 
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE,
                     "attributes-natural-language", NULL, language->language);
@@ -450,8 +752,11 @@ static int cups_job_pause(int snum, struct printjob *pjob)
 
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "job-uri", NULL, uri);
 
+       if (!push_utf8_talloc(frame, &user, pjob->user, &size)) {
+               goto out;
+       }
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name",
-                    NULL, pjob->user);
+                    NULL, user);
 
        /*
        * Do the request and get back a response...
@@ -479,6 +784,7 @@ static int cups_job_pause(int snum, struct printjob *pjob)
        if (http)
                httpClose(http);
 
+       TALLOC_FREE(frame);
        return ret;
 }
 
@@ -489,13 +795,15 @@ static int cups_job_pause(int snum, struct printjob *pjob)
 
 static int cups_job_resume(int snum, struct printjob *pjob)
 {
+       TALLOC_CTX *frame = talloc_stackframe();
        int             ret = 1;                /* Return value */
        http_t          *http = NULL;           /* HTTP connection to server */
        ipp_t           *request = NULL,        /* IPP Request */
                        *response = NULL;       /* IPP Response */
        cups_lang_t     *language = NULL;       /* Default language */
+       char *user = NULL;
        char            uri[HTTP_MAX_URI]; /* printer-uri attribute */
-
+       size_t size;
 
        DEBUG(5,("cups_job_resume(%d, %p (%d))\n", snum, pjob, pjob->sysjob));
 
@@ -509,7 +817,7 @@ static int cups_job_resume(int snum, struct printjob *pjob)
        * Try to connect to the server...
        */
 
-       if ((http = cups_connect()) == NULL) {
+       if ((http = cups_connect(frame)) == NULL) {
                goto out;
        }
 
@@ -531,7 +839,7 @@ static int cups_job_resume(int snum, struct printjob *pjob)
        language = cupsLangDefault();
 
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_CHARSET,
-                    "attributes-charset", NULL, cupsLangEncoding(language));
+                     "attributes-charset", NULL, "utf-8");
 
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE,
                     "attributes-natural-language", NULL, language->language);
@@ -540,8 +848,11 @@ static int cups_job_resume(int snum, struct printjob *pjob)
 
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "job-uri", NULL, uri);
 
+       if (!push_utf8_talloc(frame, &user, pjob->user, &size)) {
+               goto out;
+       }
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name",
-                    NULL, pjob->user);
+                    NULL, user);
 
        /*
        * Do the request and get back a response...
@@ -569,6 +880,7 @@ static int cups_job_resume(int snum, struct printjob *pjob)
        if (http)
                httpClose(http);
 
+       TALLOC_FREE(frame);
        return ret;
 }
 
@@ -579,6 +891,7 @@ static int cups_job_resume(int snum, struct printjob *pjob)
 
 static int cups_job_submit(int snum, struct printjob *pjob)
 {
+       TALLOC_CTX *frame = talloc_stackframe();
        int             ret = 1;                /* Return value */
        http_t          *http = NULL;           /* HTTP connection to server */
        ipp_t           *request = NULL,        /* IPP Request */
@@ -589,6 +902,12 @@ static int cups_job_submit(int snum, struct printjob *pjob)
        char *new_jobname = NULL;
        int             num_options = 0;
        cups_option_t   *options = NULL;
+       char *printername = NULL;
+       char *user = NULL;
+       char *jobname = NULL;
+       char *cupsoptions = NULL;
+       char *filename = NULL;
+       size_t size;
        char addr[INET6_ADDRSTRLEN];
 
        DEBUG(5,("cups_job_submit(%d, %p (%d))\n", snum, pjob, pjob->sysjob));
@@ -603,7 +922,7 @@ static int cups_job_submit(int snum, struct printjob *pjob)
        * Try to connect to the server...
        */
 
-       if ((http = cups_connect()) == NULL) {
+       if ((http = cups_connect(frame)) == NULL) {
                goto out;
        }
 
@@ -626,19 +945,25 @@ static int cups_job_submit(int snum, struct printjob *pjob)
        language = cupsLangDefault();
 
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_CHARSET,
-                    "attributes-charset", NULL, cupsLangEncoding(language));
+                     "attributes-charset", NULL, "utf-8");
 
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE,
                     "attributes-natural-language", NULL, language->language);
 
+       if (!push_utf8_talloc(frame, &printername, PRINTERNAME(snum), &size)) {
+               goto out;
+       }
        slprintf(uri, sizeof(uri) - 1, "ipp://localhost/printers/%s",
-                PRINTERNAME(snum));
+                printername);
 
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI,
                     "printer-uri", NULL, uri);
 
+       if (!push_utf8_talloc(frame, &user, pjob->user, &size)) {
+               goto out;
+       }
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name",
-                    NULL, pjob->user);
+                    NULL, user);
 
        clientname = client_name(get_client_fd());
        if (strcmp(clientname, "UNKNOWN") == 0) {
@@ -649,31 +974,43 @@ static int cups_job_submit(int snum, struct printjob *pjob)
                     "job-originating-host-name", NULL,
                      clientname);
 
-       if (asprintf(&new_jobname,"%s%.8u %s", PRINT_SPOOL_PREFIX,
-                       (unsigned int)pjob->smbjob, pjob->jobname) < 0) {
+       if (!push_utf8_talloc(frame, &jobname, pjob->jobname, &size)) {
+               goto out;
+       }
+       new_jobname = talloc_asprintf(frame,
+                       "%s%.8u %s", PRINT_SPOOL_PREFIX,
+                       (unsigned int)pjob->smbjob,
+                       jobname);
+       if (new_jobname == NULL) {
                goto out;
        }
 
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME, "job-name", NULL,
                     new_jobname);
 
-       /* 
-        * add any options defined in smb.conf 
+       /*
+        * add any options defined in smb.conf
         */
 
+       if (!push_utf8_talloc(frame, &cupsoptions, lp_cups_options(snum), &size)) {
+               goto out;
+       }
        num_options = 0;
        options     = NULL;
-       num_options = cupsParseOptions(lp_cups_options(snum), num_options, &options);
+       num_options = cupsParseOptions(cupsoptions, num_options, &options);
 
        if ( num_options )
-               cupsEncodeOptions(request, num_options, options); 
+               cupsEncodeOptions(request, num_options, options);
 
        /*
        * Do the request and get back a response...
        */
 
-       slprintf(uri, sizeof(uri) - 1, "/printers/%s", PRINTERNAME(snum));
+       slprintf(uri, sizeof(uri) - 1, "/printers/%s", printername);
 
+       if (!push_utf8_talloc(frame, &filename, pjob->filename, &size)) {
+               goto out;
+       }
        if ((response = cupsDoFileRequest(http, request, uri, pjob->filename)) != NULL) {
                if (response->request.status.status_code >= IPP_OK_CONFLICT) {
                        DEBUG(0,("Unable to print file to %s - %s\n", PRINTERNAME(snum),
@@ -700,7 +1037,7 @@ static int cups_job_submit(int snum, struct printjob *pjob)
        if (http)
                httpClose(http);
 
-       SAFE_FREE(new_jobname);
+       TALLOC_FREE(frame);
 
        return ret;
 }
@@ -712,10 +1049,11 @@ static int cups_job_submit(int snum, struct printjob *pjob)
 static int cups_queue_get(const char *sharename,
                enum printing_types printing_type,
                char *lpq_command,
-               print_queue_struct **q, 
+               print_queue_struct **q,
                print_status_struct *status)
 {
-       fstring         printername;
+       TALLOC_CTX *frame = talloc_stackframe();
+       char *printername = NULL;
        http_t          *http = NULL;           /* HTTP connection to server */
        ipp_t           *request = NULL,        /* IPP Request */
                        *response = NULL;       /* IPP Response */
@@ -726,13 +1064,14 @@ static int cups_queue_get(const char *sharename,
                        qalloc = 0;             /* Number of queue entries allocated */
        print_queue_struct *queue = NULL,       /* Queue entries */
                        *temp;          /* Temporary pointer for queue */
-       const char      *user_name,     /* job-originating-user-name attribute */
-                       *job_name;      /* job-name attribute */
+       char            *user_name = NULL,      /* job-originating-user-name attribute */
+                       *job_name = NULL;       /* job-name attribute */
        int             job_id;         /* job-id attribute */
        int             job_k_octets;   /* job-k-octets attribute */
        time_t          job_time;       /* time-at-creation attribute */
        ipp_jstate_t    job_status;     /* job-status attribute */
        int             job_priority;   /* job-priority attribute */
+       size_t size;
        static const char *jattrs[] =   /* Requested job attributes */
                        {
                          "job-id",
@@ -751,15 +1090,16 @@ static int cups_queue_get(const char *sharename,
 
        *q = NULL;
 
-       /* HACK ALERT!!!  The problem with support the 'printer name' 
-          option is that we key the tdb off the sharename.  So we will 
-          overload the lpq_command string to pass in the printername 
-          (which is basically what we do for non-cups printers ... using 
+       /* HACK ALERT!!!  The problem with support the 'printer name'
+          option is that we key the tdb off the sharename.  So we will
+          overload the lpq_command string to pass in the printername
+          (which is basically what we do for non-cups printers ... using
           the lpq_command to get the queue listing). */
 
-       fstrcpy( printername, lpq_command );
-
-       DEBUG(5,("cups_queue_get(%s, %p, %p)\n", printername, q, status));
+       if (!push_utf8_talloc(frame, &printername, lpq_command, &size)) {
+               goto out;
+       }
+       DEBUG(5,("cups_queue_get(%s, %p, %p)\n", lpq_command, q, status));
 
        /*
         * Make sure we don't ask for passwords...
@@ -771,7 +1111,7 @@ static int cups_queue_get(const char *sharename,
        * Try to connect to the server...
        */
 
-       if ((http = cups_connect()) == NULL) {
+       if ((http = cups_connect(frame)) == NULL) {
                goto out;
        }
 
@@ -799,7 +1139,7 @@ static int cups_queue_get(const char *sharename,
        language = cupsLangDefault();
 
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_CHARSET,
-                     "attributes-charset", NULL, cupsLangEncoding(language));
+                     "attributes-charset", NULL, "utf-8");
 
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE,
                      "attributes-natural-language", NULL, language->language);
@@ -904,12 +1244,24 @@ static int cups_queue_get(const char *sharename,
                                job_time = attr->values[0].integer;
 
                        if (strcmp(attr->name, "job-name") == 0 &&
-                           attr->value_tag == IPP_TAG_NAME)
-                               job_name = attr->values[0].string.text;
+                           attr->value_tag == IPP_TAG_NAME) {
+                               if (!pull_utf8_talloc(frame,
+                                               &job_name,
+                                               attr->values[0].string.text,
+                                               &size)) {
+                                       goto out;
+                               }
+                       }
 
                        if (strcmp(attr->name, "job-originating-user-name") == 0 &&
-                           attr->value_tag == IPP_TAG_NAME)
-                               user_name = attr->values[0].string.text;
+                           attr->value_tag == IPP_TAG_NAME) {
+                               if (!pull_utf8_talloc(frame,
+                                               &user_name,
+                                               attr->values[0].string.text,
+                                               &size)) {
+                                       goto out;
+                               }
+                       }
 
                        attr = attr->next;
                }
@@ -933,8 +1285,8 @@ static int cups_queue_get(const char *sharename,
                                 LPQ_PRINTING;
                temp->priority = job_priority;
                temp->time     = job_time;
-               strncpy(temp->fs_user, user_name, sizeof(temp->fs_user) - 1);
-               strncpy(temp->fs_file, job_name, sizeof(temp->fs_file) - 1);
+               strlcpy(temp->fs_user, user_name, sizeof(temp->fs_user));
+               strlcpy(temp->fs_file, job_name, sizeof(temp->fs_file));
 
                qcount ++;
 
@@ -961,7 +1313,7 @@ static int cups_queue_get(const char *sharename,
        request->request.op.request_id   = 1;
 
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_CHARSET,
-                     "attributes-charset", NULL, cupsLangEncoding(language));
+                     "attributes-charset", NULL, "utf-8");
 
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE,
                      "attributes-natural-language", NULL, language->language);
@@ -1004,8 +1356,15 @@ static int cups_queue_get(const char *sharename,
        }
 
         if ((attr = ippFindAttribute(response, "printer-state-message",
-                                    IPP_TAG_TEXT)) != NULL)
-               fstrcpy(status->message, attr->values[0].string.text);
+                                    IPP_TAG_TEXT)) != NULL) {
+               char *msg = NULL;
+               if (!pull_utf8_talloc(frame, &msg,
+                               attr->values[0].string.text,
+                               &size)) {
+                       goto out;
+               }
+               fstrcpy(status->message, msg);
+       }
 
        /*
         * Return the job queue...
@@ -1023,6 +1382,7 @@ static int cups_queue_get(const char *sharename,
        if (http)
                httpClose(http);
 
+       TALLOC_FREE(frame);
        return qcount;
 }
 
@@ -1033,13 +1393,16 @@ static int cups_queue_get(const char *sharename,
 
 static int cups_queue_pause(int snum)
 {
+       TALLOC_CTX *frame = talloc_stackframe();
        int             ret = 1;                /* Return value */
        http_t          *http = NULL;           /* HTTP connection to server */
        ipp_t           *request = NULL,        /* IPP Request */
                        *response = NULL;       /* IPP Response */
        cups_lang_t     *language = NULL;       /* Default language */
+       char *printername = NULL;
+       char *username = NULL;
        char            uri[HTTP_MAX_URI]; /* printer-uri attribute */
-
+       size_t size;
 
        DEBUG(5,("cups_queue_pause(%d)\n", snum));
 
@@ -1053,7 +1416,7 @@ static int cups_queue_pause(int snum)
         * Try to connect to the server...
         */
 
-       if ((http = cups_connect()) == NULL) {
+       if ((http = cups_connect(frame)) == NULL) {
                goto out;
        }
 
@@ -1075,18 +1438,24 @@ static int cups_queue_pause(int snum)
        language = cupsLangDefault();
 
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_CHARSET,
-                    "attributes-charset", NULL, cupsLangEncoding(language));
+                     "attributes-charset", NULL, "utf-8");
 
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE,
                     "attributes-natural-language", NULL, language->language);
 
+       if (!push_utf8_talloc(frame, &printername, PRINTERNAME(snum), &size)) {
+               goto out;
+       }
        slprintf(uri, sizeof(uri) - 1, "ipp://localhost/printers/%s",
-                PRINTERNAME(snum));
+                printername);
 
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, uri);
 
+       if (!push_utf8_talloc(frame, &username, current_user_info.unix_name, &size)) {
+               goto out;
+       }
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name",
-                    NULL, current_user_info.unix_name);
+                    NULL, username);
 
        /*
        * Do the request and get back a response...
@@ -1114,6 +1483,7 @@ static int cups_queue_pause(int snum)
        if (http)
                httpClose(http);
 
+       TALLOC_FREE(frame);
        return ret;
 }
 
@@ -1124,13 +1494,16 @@ static int cups_queue_pause(int snum)
 
 static int cups_queue_resume(int snum)
 {
+       TALLOC_CTX *frame = talloc_stackframe();
        int             ret = 1;                /* Return value */
        http_t          *http = NULL;           /* HTTP connection to server */
        ipp_t           *request = NULL,        /* IPP Request */
                        *response = NULL;       /* IPP Response */
        cups_lang_t     *language = NULL;       /* Default language */
+       char *printername = NULL;
+       char *username = NULL;
        char            uri[HTTP_MAX_URI]; /* printer-uri attribute */
-
+       size_t size;
 
        DEBUG(5,("cups_queue_resume(%d)\n", snum));
 
@@ -1144,7 +1517,7 @@ static int cups_queue_resume(int snum)
        * Try to connect to the server...
        */
 
-       if ((http = cups_connect()) == NULL) {
+       if ((http = cups_connect(frame)) == NULL) {
                goto out;
        }
 
@@ -1166,18 +1539,24 @@ static int cups_queue_resume(int snum)
        language = cupsLangDefault();
 
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_CHARSET,
-                    "attributes-charset", NULL, cupsLangEncoding(language));
+                     "attributes-charset", NULL, "utf-8");
 
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE,
                     "attributes-natural-language", NULL, language->language);
 
+       if (!push_utf8_talloc(frame, &printername, PRINTERNAME(snum), &size)) {
+               goto out;
+       }
        slprintf(uri, sizeof(uri) - 1, "ipp://localhost/printers/%s",
-                PRINTERNAME(snum));
+                printername);
 
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, uri);
 
+       if (!push_utf8_talloc(frame, &username, current_user_info.unix_name, &size)) {
+               goto out;
+       }
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name",
-                    NULL, current_user_info.unix_name);
+                    NULL, username);
 
        /*
        * Do the request and get back a response...
@@ -1205,6 +1584,7 @@ static int cups_queue_resume(int snum)
        if (http)
                httpClose(http);
 
+       TALLOC_FREE(frame);
        return ret;
 }
 
@@ -1226,15 +1606,16 @@ struct printif  cups_printif =
 
 bool cups_pull_comment_location(NT_PRINTER_INFO_LEVEL_2 *printer)
 {
+       TALLOC_CTX *frame = talloc_stackframe();
        http_t          *http = NULL;           /* HTTP connection to server */
        ipp_t           *request = NULL,        /* IPP Request */
                        *response = NULL;       /* IPP Response */
        ipp_attribute_t *attr;          /* Current attribute */
        cups_lang_t     *language = NULL;       /* Default language */
-       char            *name,          /* printer-name attribute */
-                       *info,          /* printer-info attribute */
-                       *location;      /* printer-location attribute */
        char            uri[HTTP_MAX_URI];
+       char *server = NULL;
+       char *sharename = NULL;
+       char *name = NULL;
        static const char *requested[] =/* Requested attributes */
                        {
                          "printer-name",
@@ -1242,6 +1623,7 @@ bool cups_pull_comment_location(NT_PRINTER_INFO_LEVEL_2 *printer)
                          "printer-location"
                        };
        bool ret = False;
+       size_t size;
 
        DEBUG(5, ("pulling %s location\n", printer->sharename));
 
@@ -1255,7 +1637,7 @@ bool cups_pull_comment_location(NT_PRINTER_INFO_LEVEL_2 *printer)
         * Try to connect to the server...
         */
 
-       if ((http = cups_connect()) == NULL) {
+       if ((http = cups_connect(frame)) == NULL) {
                goto out;
        }
 
@@ -1267,13 +1649,26 @@ bool cups_pull_comment_location(NT_PRINTER_INFO_LEVEL_2 *printer)
        language = cupsLangDefault();
 
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_CHARSET,
-                     "attributes-charset", NULL, cupsLangEncoding(language));
+                     "attributes-charset", NULL, "utf-8");
 
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE,
                      "attributes-natural-language", NULL, language->language);
 
+       if (lp_cups_server() != NULL && strlen(lp_cups_server()) > 0) {
+               if (!push_utf8_talloc(frame, &server, lp_cups_server(), &size)) {
+                       goto out;
+               }
+       } else {
+               server = talloc_strdup(frame,cupsServer());
+       }
+       if (server) {
+               goto out;
+       }
+       if (!push_utf8_talloc(frame, &sharename, printer->sharename, &size)) {
+               goto out;
+       }
        slprintf(uri, sizeof(uri) - 1, "ipp://%s/printers/%s",
-                lp_cups_server(), printer->sharename);
+                server, sharename);
 
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI,
                      "printer-uri", NULL, uri);
@@ -1308,43 +1703,64 @@ bool cups_pull_comment_location(NT_PRINTER_INFO_LEVEL_2 *printer)
                 * Pull the needed attributes from this printer...
                 */
 
-               name       = NULL;
-               info       = NULL;
-               location   = NULL;
-
                while ( attr && (attr->group_tag == IPP_TAG_PRINTER) ) {
+                       if (strcmp(attr->name, "printer-name") == 0 &&
+                           attr->value_tag == IPP_TAG_NAME) {
+                               if (!pull_utf8_talloc(frame,
+                                               &name,
+                                               attr->values[0].string.text,
+                                               &size)) {
+                                       goto out;
+                               }
+                       }
+
                        /* Grab the comment if we don't have one */
                        if ( (strcmp(attr->name, "printer-info") == 0)
                             && (attr->value_tag == IPP_TAG_TEXT)
-                            && !strlen(printer->comment) ) 
+                            && !strlen(printer->comment) )
                        {
+                               char *comment = NULL;
+                               if (!pull_utf8_talloc(frame,
+                                               &comment,
+                                               attr->values[0].string.text,
+                                               &size)) {
+                                       goto out;
+                               }
                                DEBUG(5,("cups_pull_comment_location: Using cups comment: %s\n",
-                                        attr->values[0].string.text));                         
+                                        comment));
                                strlcpy(printer->comment,
-                                               attr->values[0].string.text,
-                                               sizeof(printer->comment));
+                                       comment,
+                                       sizeof(printer->comment));
                        }
 
-                       /* Grab the location if we don't have one */ 
+                       /* Grab the location if we don't have one */
                        if ( (strcmp(attr->name, "printer-location") == 0)
-                            && (attr->value_tag == IPP_TAG_TEXT) 
+                            && (attr->value_tag == IPP_TAG_TEXT)
                             && !strlen(printer->location) )
                        {
+                               char *location = NULL;
+                               if (!pull_utf8_talloc(frame,
+                                               &location,
+                                               attr->values[0].string.text,
+                                               &size)) {
+                                       goto out;
+                               }
                                DEBUG(5,("cups_pull_comment_location: Using cups location: %s\n",
-                                        attr->values[0].string.text));                         
-                               fstrcpy(printer->location,attr->values[0].string.text);
+                                        location));
+                               strlcpy(printer->location,
+                                       location,
+                                       sizeof(printer->location));
                        }
 
                        attr = attr->next;
                }
 
                /*
-                * See if we have everything needed...
+                * We have everything needed...
                 */
 
-               if (name == NULL)
+               if (name != NULL)
                        break;
-
        }
 
        ret = True;
@@ -1359,6 +1775,7 @@ bool cups_pull_comment_location(NT_PRINTER_INFO_LEVEL_2 *printer)
        if (http)
                httpClose(http);
 
+       TALLOC_FREE(frame);
        return ret;
 }
 
index c68ecdedebcd01014a32cd57505af0de5a5f91b8..d06410a1b37f1995b231a01300b544cf9b3b4f94 100644 (file)
@@ -37,7 +37,6 @@ static const struct generic_mapping reg_generic_map =
 static WERROR construct_registry_sd(TALLOC_CTX *ctx, SEC_DESC **psd)
 {
        SEC_ACE ace[3];
-       SEC_ACCESS mask;
        size_t i = 0;
        SEC_DESC *sd;
        SEC_ACL *acl;
@@ -45,21 +44,18 @@ static WERROR construct_registry_sd(TALLOC_CTX *ctx, SEC_DESC **psd)
 
        /* basic access for Everyone */
 
-       init_sec_access(&mask, REG_KEY_READ);
        init_sec_ace(&ace[i++], &global_sid_World, SEC_ACE_TYPE_ACCESS_ALLOWED,
-                    mask, 0);
+                    REG_KEY_READ, 0);
 
        /* Full Access 'BUILTIN\Administrators' */
 
-       init_sec_access(&mask, REG_KEY_ALL);
        init_sec_ace(&ace[i++], &global_sid_Builtin_Administrators,
-                    SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
+                    SEC_ACE_TYPE_ACCESS_ALLOWED, REG_KEY_ALL, 0);
 
        /* Full Access 'NT Authority\System' */
 
-       init_sec_access(&mask, REG_KEY_ALL );
        init_sec_ace(&ace[i++], &global_sid_System, SEC_ACE_TYPE_ACCESS_ALLOWED,
-                    mask, 0);
+                    REG_KEY_ALL, 0);
 
        /* create the security descriptor */
 
index 94517f347879f1d779b217a46eea169548d8714f..0e9d12124217112162ae344e3c5e63bad3c1329b 100644 (file)
@@ -290,22 +290,18 @@ static NTSTATUS lsa_get_generic_sd(TALLOC_CTX *mem_ctx, SEC_DESC **sd, size_t *s
        DOM_SID adm_sid;
 
        SEC_ACE ace[3];
-       SEC_ACCESS mask;
 
        SEC_ACL *psa = NULL;
 
-       init_sec_access(&mask, LSA_POLICY_EXECUTE);
-       init_sec_ace(&ace[0], &global_sid_World, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
+       init_sec_ace(&ace[0], &global_sid_World, SEC_ACE_TYPE_ACCESS_ALLOWED, LSA_POLICY_EXECUTE, 0);
 
        sid_copy(&adm_sid, get_global_sam_sid());
        sid_append_rid(&adm_sid, DOMAIN_GROUP_RID_ADMINS);
-       init_sec_access(&mask, LSA_POLICY_ALL_ACCESS);
-       init_sec_ace(&ace[1], &adm_sid, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
+       init_sec_ace(&ace[1], &adm_sid, SEC_ACE_TYPE_ACCESS_ALLOWED, LSA_POLICY_ALL_ACCESS, 0);
 
        sid_copy(&local_adm_sid, &global_sid_Builtin);
        sid_append_rid(&local_adm_sid, BUILTIN_ALIAS_RID_ADMINS);
-       init_sec_access(&mask, LSA_POLICY_ALL_ACCESS);
-       init_sec_ace(&ace[2], &local_adm_sid, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
+       init_sec_ace(&ace[2], &local_adm_sid, SEC_ACE_TYPE_ACCESS_ALLOWED, LSA_POLICY_ALL_ACCESS, 0);
 
        if((psa = make_sec_acl(mem_ctx, NT4_ACL_REVISION, 3, ace)) == NULL)
                return NT_STATUS_NO_MEMORY;
index 1b1e98c049cc0ade0cdc9d7bcec8d9b8b8d2eccc..6455f0237496dd1f8d4ab4a9df9ae14554ab1627 100644 (file)
@@ -113,36 +113,35 @@ static NTSTATUS make_samr_object_sd( TALLOC_CTX *ctx, SEC_DESC **psd, size_t *sd
 {
        DOM_SID domadmin_sid;
        SEC_ACE ace[5];         /* at most 5 entries */
-       SEC_ACCESS mask;
        size_t i = 0;
 
        SEC_ACL *psa = NULL;
 
        /* basic access for Everyone */
 
-       init_sec_access(&mask, map->generic_execute | map->generic_read );
-       init_sec_ace(&ace[i++], &global_sid_World, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
+       init_sec_ace(&ace[i++], &global_sid_World, SEC_ACE_TYPE_ACCESS_ALLOWED,
+                       map->generic_execute | map->generic_read, 0);
 
        /* add Full Access 'BUILTIN\Administrators' and 'BUILTIN\Account Operators */
 
-       init_sec_access(&mask, map->generic_all);
-
-       init_sec_ace(&ace[i++], &global_sid_Builtin_Administrators, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
-       init_sec_ace(&ace[i++], &global_sid_Builtin_Account_Operators, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
+       init_sec_ace(&ace[i++], &global_sid_Builtin_Administrators,
+                       SEC_ACE_TYPE_ACCESS_ALLOWED, map->generic_all, 0);
+       init_sec_ace(&ace[i++], &global_sid_Builtin_Account_Operators,
+                       SEC_ACE_TYPE_ACCESS_ALLOWED, map->generic_all, 0);
 
        /* Add Full Access for Domain Admins if we are a DC */
 
        if ( IS_DC ) {
                sid_copy( &domadmin_sid, get_global_sam_sid() );
                sid_append_rid( &domadmin_sid, DOMAIN_GROUP_RID_ADMINS );
-               init_sec_ace(&ace[i++], &domadmin_sid, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
+               init_sec_ace(&ace[i++], &domadmin_sid,
+                       SEC_ACE_TYPE_ACCESS_ALLOWED, map->generic_all, 0);
        }
 
        /* if we have a sid, give it some special access */
 
        if ( sid ) {
-               init_sec_access( &mask, sid_access );
-               init_sec_ace(&ace[i++], sid, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
+               init_sec_ace(&ace[i++], sid, SEC_ACE_TYPE_ACCESS_ALLOWED, sid_access, 0);
        }
 
        /* create the security descriptor */
index bb9c3687fbc6d86483e1542306c479950973a408..47688b114c8ad7246209aa54b58c46357811d3d7 100644 (file)
@@ -1700,7 +1700,9 @@ WERROR _srvsvc_NetShareAdd(pipes_struct *p,
 
        DEBUG(5,("_srvsvc_NetShareAdd: %d\n", __LINE__));
 
-       *r->out.parm_error = 0;
+       if (r->out.parm_error) {
+               *r->out.parm_error = 0;
+       }
 
        get_current_user(&user,p);
 
@@ -2148,6 +2150,8 @@ WERROR _srvsvc_NetSetFileSecurity(pipes_struct *p,
        connection_struct *conn = NULL;
        int snum;
        char *oldcwd = NULL;
+       struct security_descriptor *psd = NULL;
+       uint32_t security_info_sent = 0;
 
        ZERO_STRUCT(st);
 
@@ -2196,9 +2200,29 @@ WERROR _srvsvc_NetSetFileSecurity(pipes_struct *p,
                goto error_exit;
        }
 
+       psd = r->in.sd_buf->sd;
+       security_info_sent = r->in.securityinformation;
+
+       if (psd->owner_sid==0) {
+               security_info_sent &= ~OWNER_SECURITY_INFORMATION;
+       }
+       if (psd->group_sid==0) {
+               security_info_sent &= ~GROUP_SECURITY_INFORMATION;
+       }
+       if (psd->sacl==0) {
+               security_info_sent &= ~SACL_SECURITY_INFORMATION;
+       }
+       if (psd->dacl==0) {
+               security_info_sent &= ~DACL_SECURITY_INFORMATION;
+       }
+
+       /* Convert all the generic bits. */
+       security_acl_map_generic(psd->dacl, &file_generic_mapping);
+       security_acl_map_generic(psd->sacl, &file_generic_mapping);
+
        nt_status = SMB_VFS_FSET_NT_ACL(fsp,
-                                      r->in.securityinformation,
-                                      r->in.sd_buf->sd);
+                                       security_info_sent,
+                                       psd);
 
        if (!NT_STATUS_IS_OK(nt_status) ) {
                DEBUG(3,("_srvsvc_NetSetFileSecurity: Unable to set NT ACL "
index 6bb538a3115384a3c148287fbfcb5b69c238f6bd..a57d0ff4a4f914135762f690ec8d0846e2cb692d 100644 (file)
@@ -140,7 +140,6 @@ static NTSTATUS svcctl_access_check( SEC_DESC *sec_desc, NT_USER_TOKEN *token,
 static SEC_DESC* construct_scm_sd( TALLOC_CTX *ctx )
 {
        SEC_ACE ace[2];
-       SEC_ACCESS mask;
        size_t i = 0;
        SEC_DESC *sd;
        SEC_ACL *acl;
@@ -148,13 +147,13 @@ static SEC_DESC* construct_scm_sd( TALLOC_CTX *ctx )
 
        /* basic access for Everyone */
 
-       init_sec_access(&mask, SC_MANAGER_READ_ACCESS );
-       init_sec_ace(&ace[i++], &global_sid_World, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
+       init_sec_ace(&ace[i++], &global_sid_World,
+               SEC_ACE_TYPE_ACCESS_ALLOWED, SC_MANAGER_READ_ACCESS, 0);
 
        /* Full Access 'BUILTIN\Administrators' */
 
-       init_sec_access(&mask,SC_MANAGER_ALL_ACCESS );
-       init_sec_ace(&ace[i++], &global_sid_Builtin_Administrators, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
+       init_sec_ace(&ace[i++], &global_sid_Builtin_Administrators,
+               SEC_ACE_TYPE_ACCESS_ALLOWED, SC_MANAGER_ALL_ACCESS, 0);
 
 
        /* create the security descriptor */
index 728fd2d45d907688dca7eeb2ec3c35e202c6dbc4..81f1809210c7e49fc23c65bc2dc339313641be7c 100644 (file)
@@ -35,7 +35,7 @@ SMB_EXT_LIB_FROM_PKGCONFIG(LIBTALLOC, talloc >= 1.2.0,
        ]
 )
 
-SMB_EXT_LIB_FROM_PKGCONFIG(LIBTDB, tdb >= 1.1.0,
+SMB_EXT_LIB_FROM_PKGCONFIG(LIBTDB, tdb >= 1.1.3,
        [],
        [
                m4_include(../lib/tdb/libtdb.m4)
index 53ea76ed90fab54ba440b1e0b2be804e30e73a77..524fc9f64ce1ed7f761395734167c6cfae0a5492 100644 (file)
@@ -87,7 +87,7 @@ libstreamsrcdir := $(samba4srcdir)/lib/stream
 libutilsrcdir := $(samba4srcdir)/lib/util
 libtdrsrcdir := $(samba4srcdir)/lib/tdr
 libdbwrapsrcdir := $(samba4srcdir)/lib/dbwrap
-libcryptosrcdir := $(samba4srcdir)/lib/crypto
+libcryptosrcdir := $(samba4srcdir)/../lib/crypto
 libtorturesrcdir := $(samba4srcdir)/lib/torture
 libcompressionsrcdir := $(samba4srcdir)/../lib/compression
 libgencachesrcdir := $(samba4srcdir)/lib
@@ -107,7 +107,7 @@ ntvfssrcdir := $(samba4srcdir)/ntvfs
 ntptrsrcdir := $(samba4srcdir)/ntptr
 clientsrcdir := $(samba4srcdir)/client
 libclisrcdir := $(samba4srcdir)/libcli
-libclinbtsrcdir := $(samba4srcdir)/../libcli
+libclinbtsrcdir := $(samba4srcdir)/../libcli/nbt
 pyscriptsrcdir := $(samba4srcdir)/scripting/python
 kdcsrcdir := $(samba4srcdir)/kdc
 smbreadlinesrcdir := $(samba4srcdir)/lib/smbreadline
diff --git a/source3/script/tests/wb_pad.sh b/source3/script/tests/wb_pad.sh
new file mode 100755 (executable)
index 0000000..f1f5ca2
--- /dev/null
@@ -0,0 +1,82 @@
+#!/bin/sh
+#
+# Copyright (C) Guenther Deschner 2008
+#
+# 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/>.
+
+tempdir=`mktemp -d /tmp/wb_padXXXXXX`
+test -n "$tempdir" || exit 1
+cat >> $tempdir/wb_pad.c << _EOF
+#include "nsswitch/winbind_client.h"
+
+int main(int argc, const char **argv)
+{
+       struct winbindd_request req;
+       struct winbindd_response resp;
+
+       if (argc != 2) {
+               printf("usage: %s [req|resp]\n", argv[0]);
+               return 0;
+       }
+
+       if (strcmp(argv[1], "req") == 0) {
+               printf("%d\n", (uint32_t)sizeof(req));
+       }
+       if (strcmp(argv[1], "resp") == 0) {
+               printf("%d\n", (uint32_t)sizeof(resp));
+       }
+
+       return 0;
+}
+_EOF
+
+cleanup() {
+       rm -f $tempdir/wb_pad_32 $tempdir/wb_pad_64 $tempdir/wb_pad.c
+       rmdir $tempdir
+}
+
+cflags="-I. -I./../lib/replace -Iinclude"
+${CC:-gcc} -m32 $RPM_OPT_FLAGS $CFLAGS -o $tempdir/wb_pad_32 $cflags $tempdir/wb_pad.c
+if [ $? -ne 0 ]; then
+       cleanup
+       exit 1
+fi
+${CC:-gcc} -m64 $RPM_OPT_FLAGS $CFLAGS -o $tempdir/wb_pad_64 $cflags $tempdir/wb_pad.c
+if [ $? -ne 0 ]; then
+       cleanup
+       exit 1
+fi
+
+out_64_req=`$tempdir/wb_pad_64 req`
+out_64_resp=`$tempdir/wb_pad_64 resp`
+out_32_req=`$tempdir/wb_pad_32 req`
+out_32_resp=`$tempdir/wb_pad_32 resp`
+
+cleanup
+
+if test "$out_64_req" != "$out_32_req"; then
+       echo "winbind request size differs!"
+       echo "64bit: $out_64_req"
+       echo "32bit: $out_32_req"
+       exit 1
+fi
+
+if test "$out_64_resp" != "$out_32_resp"; then
+       echo "winbind response size differs!"
+       echo "64bit: $out_64_resp"
+       echo "32bit: $out_32_resp"
+       exit 1
+fi
+
+exit 0
index 8f58c2dbfa0baafea5168a25537423c6217f6f11..0f5264bcd859c0b6a46c8da146a84de1f41dea58 100644 (file)
@@ -89,7 +89,6 @@ struct service_display_info common_unix_svcs[] = {
 static SEC_DESC* construct_service_sd( TALLOC_CTX *ctx )
 {
        SEC_ACE ace[4];
-       SEC_ACCESS mask;
        size_t i = 0;
        SEC_DESC *sd = NULL;
        SEC_ACL *acl = NULL;
@@ -97,15 +96,16 @@ static SEC_DESC* construct_service_sd( TALLOC_CTX *ctx )
 
        /* basic access for Everyone */
 
-       init_sec_access(&mask, SERVICE_READ_ACCESS );
-       init_sec_ace(&ace[i++], &global_sid_World, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
+       init_sec_ace(&ace[i++], &global_sid_World,
+               SEC_ACE_TYPE_ACCESS_ALLOWED, SERVICE_READ_ACCESS, 0);
 
-       init_sec_access(&mask,SERVICE_EXECUTE_ACCESS );
-       init_sec_ace(&ace[i++], &global_sid_Builtin_Power_Users, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
+       init_sec_ace(&ace[i++], &global_sid_Builtin_Power_Users,
+                       SEC_ACE_TYPE_ACCESS_ALLOWED, SERVICE_EXECUTE_ACCESS, 0);
 
-       init_sec_access(&mask,SERVICE_ALL_ACCESS );
-       init_sec_ace(&ace[i++], &global_sid_Builtin_Server_Operators, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
-       init_sec_ace(&ace[i++], &global_sid_Builtin_Administrators, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
+       init_sec_ace(&ace[i++], &global_sid_Builtin_Server_Operators,
+               SEC_ACE_TYPE_ACCESS_ALLOWED, SERVICE_ALL_ACCESS, 0);
+       init_sec_ace(&ace[i++], &global_sid_Builtin_Administrators,
+               SEC_ACE_TYPE_ACCESS_ALLOWED, SERVICE_ALL_ACCESS, 0);
 
        /* create the security descriptor */
 
index b9433bb96580385a7312efe1e2afec17dc2941de..7f34d2b8e2b3e9d1971c2bd9cb9a9e5057b1c32c 100644 (file)
@@ -252,8 +252,8 @@ void conn_free_internal(connection_struct *conn)
        /* Free vfs_connection_struct */
        handle = conn->vfs_handles;
        while(handle) {
-               DLIST_REMOVE(conn->vfs_handles, handle);
                thandle = handle->next;
+               DLIST_REMOVE(conn->vfs_handles, handle);
                if (handle->free_data)
                        handle->free_data(&handle->data);
                handle = thandle;
index 8dd5964f5f4d0472451e15c022b9c019d1d6c5f6..fd83f777253d97f1025cba0eb0c13aa6da422ed4 100644 (file)
@@ -2,17 +2,17 @@
    Unix SMB/CIFS implementation.
    connection claim routines
    Copyright (C) Andrew Tridgell 1998
-   
+
    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/>.
 */
@@ -63,7 +63,7 @@ static int count_fn(struct db_record *rec,
                    void *udp)
 {
        struct count_stat *cs = (struct count_stat *)udp;
+
        if (crec->cnum == -1) {
                return 0;
        }
@@ -159,7 +159,7 @@ bool claim_connection(connection_struct *conn, const char *name,
        }
        crec.start = time(NULL);
        crec.bcast_msg_flags = msg_flags;
-       
+
        strlcpy(crec.machine,get_remote_machine_name(),sizeof(crec.machine));
        strlcpy(crec.addr,conn?conn->client_address:
                        client_addr(get_client_fd(),addr,sizeof(addr)),
@@ -232,17 +232,17 @@ static TDB_DATA* make_pipe_rec_key( struct pipe_open_rec *prec )
 {
        TDB_DATA *kbuf = NULL;
        fstring key_string;
-       
+
        if ( !prec )
                return NULL;
-       
+
        if ( (kbuf = TALLOC_P(prec, TDB_DATA)) == NULL ) {
                return NULL;
        }
-       
+
        snprintf( key_string, sizeof(key_string), "%s/%d/%d",
                prec->name, procid_to_pid(&prec->pid), prec->pnum );
-               
+
        *kbuf = string_term_tdb_data(talloc_strdup(prec, key_string));
        if (kbuf->dptr == NULL )
                return NULL;
@@ -273,17 +273,17 @@ bool store_pipe_opendb( smb_np_struct *p )
        TDB_DATA *key;
        TDB_DATA data;
        bool ret = False;
-       
-       if ( (prec = TALLOC_P( NULL, struct pipe_open_rec)) == NULL ) {
+
+       if ( (prec = TALLOC_P( talloc_tos(), struct pipe_open_rec)) == NULL ) {
                DEBUG(0,("store_pipe_opendb: talloc failed!\n"));
                return False;
        }
-       
+
        fill_pipe_open_rec( prec, p );
        if ( (key = make_pipe_rec_key( prec )) == NULL ) {
                goto done;
        }
-       
+
        data.dptr = (uint8 *)prec;
        data.dsize = sizeof(struct pipe_open_rec);
 
@@ -293,7 +293,7 @@ bool store_pipe_opendb( smb_np_struct *p )
        }
 
        ret = NT_STATUS_IS_OK(dbrec->store(dbrec, data, TDB_REPLACE));
-       
+
 done:
        TALLOC_FREE( prec );    
        return ret;
@@ -308,24 +308,24 @@ bool delete_pipe_opendb( smb_np_struct *p )
        struct pipe_open_rec *prec;
        TDB_DATA *key;
        bool ret = False;
-       
-       if ( (prec = TALLOC_P( NULL, struct pipe_open_rec)) == NULL ) {
+
+       if ( (prec = TALLOC_P( talloc_tos(), struct pipe_open_rec)) == NULL ) {
                DEBUG(0,("store_pipe_opendb: talloc failed!\n"));
                return False;
        }
-       
+
        fill_pipe_open_rec( prec, p );
        if ( (key = make_pipe_rec_key( prec )) == NULL ) {
                goto done;
        }
-       
+
        if (!(dbrec = connections_fetch_record(prec, *key))) {
                DEBUG(0, ("connections_fetch_record failed\n"));
                goto done;
        }
 
        ret = NT_STATUS_IS_OK(dbrec->delete_rec(dbrec));
-       
+
 done:
        TALLOC_FREE( prec );
        return ret;
index 8dd9abee1ad4697ab3bba1198ba4265d3a5595e9..1761cb66a85c17b3a1b32e6a6dbd490d98150cb9 100644 (file)
@@ -146,14 +146,6 @@ NTSTATUS open_fake_file(connection_struct *conn,
        return NT_STATUS_OK;
 }
 
-void destroy_fake_file_handle(struct fake_file_handle **fh)
-{
-       if (!fh) {
-               return;
-       }
-       TALLOC_FREE(*fh);
-}
-
 NTSTATUS close_fake_file(files_struct *fsp)
 {
        file_free(fsp);
index 17c473f028bdc246de3143d3f48e9fe7bafaa346..519f4945f2268bc4c1d4c91b4fe0005d687c7eea 100644 (file)
@@ -122,10 +122,12 @@ NTSTATUS file_new(connection_struct *conn, files_struct **result)
 
        chain_fsp = fsp;
 
-       /* A new fsp invalidates a negative fsp_fi_cache. */
-       if (fsp_fi_cache.fsp == NULL) {
-               ZERO_STRUCT(fsp_fi_cache);
-       }
+       /* A new fsp invalidates the positive and
+         negative fsp_fi_cache as the new fsp is pushed
+         at the start of the list and we search from
+         a cache hit to the *end* of the list. */
+
+       ZERO_STRUCT(fsp_fi_cache);
 
        *result = fsp;
        return NT_STATUS_OK;
@@ -326,8 +328,7 @@ files_struct *file_find_di_first(struct file_id id)
        fsp_fi_cache.id = id;
 
        for (fsp=Files;fsp;fsp=fsp->next) {
-               if ( fsp->fh->fd != -1 &&
-                    file_id_equal(&fsp->file_id, &id)) {
+               if (file_id_equal(&fsp->file_id, &id)) {
                        /* Setup positive cache. */
                        fsp_fi_cache.fsp = fsp;
                        return fsp;
@@ -348,8 +349,7 @@ files_struct *file_find_di_next(files_struct *start_fsp)
        files_struct *fsp;
 
        for (fsp = start_fsp->next;fsp;fsp=fsp->next) {
-               if ( fsp->fh->fd != -1 &&
-                    file_id_equal(&fsp->file_id, &start_fsp->file_id)) {
+               if (file_id_equal(&fsp->file_id, &start_fsp->file_id)) {
                        return fsp;
                }
        }
@@ -400,9 +400,7 @@ void file_free(files_struct *fsp)
 
        string_free(&fsp->fsp_name);
 
-       if (fsp->fake_file_handle) {
-               destroy_fake_file_handle(&fsp->fake_file_handle);
-       }
+       TALLOC_FREE(fsp->fake_file_handle);
 
        if (fsp->fh->ref_count == 1) {
                SAFE_FREE(fsp->fh);
index f4c45999bab8152d72e927f69c3be04850d03265..a824ab7fd357b040f4599a2c9899fcc63f5eff29 100644 (file)
@@ -5,17 +5,17 @@
 
    SMB Version handling
    Copyright (C) John H Terpstra 1995-1998
-   
+
    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/>.
    */
@@ -162,7 +162,7 @@ void send_trans_reply(connection_struct *conn, const uint8_t *inbuf,
                copy_trans_params_and_data(outbuf, align,
                                           rparam, tot_param_sent, this_lparam,
                                           rdata, tot_data_sent, this_ldata);
-               
+
                SSVAL(outbuf,smb_vwv3,this_lparam);
                SSVAL(outbuf,smb_vwv4,smb_offset(smb_buf(outbuf)+1,outbuf));
                SSVAL(outbuf,smb_vwv5,tot_param_sent);
@@ -318,7 +318,7 @@ static void api_fd_reply(connection_struct *conn, uint16 vuid,
        /* Get the file handle and hence the file name. */
        /* 
         * NB. The setup array has already been transformed
-        * via SVAL and so is in gost byte order.
+        * via SVAL and so is in host byte order.
         */
        pnum = ((int)setup[1]) & 0xFFFF;
        subcommand = ((int)setup[0]) & 0xFFFF;
@@ -735,11 +735,11 @@ void reply_transs(struct smb_request *req)
 
        state->received_param += pcnt;
        state->received_data += dcnt;
-               
+
        if ((state->received_data > state->total_data) ||
            (state->received_param > state->total_param))
                goto bad_param;
-               
+
        if (pcnt) {
                if (pdisp > state->total_param ||
                                pcnt > state->total_param ||
index 584399c86c9331d6f93ae59616a461aa1b9f24e1..43492bf8b62043e84c72470b199db116082b1422 100644 (file)
@@ -22,6 +22,7 @@
 
 extern int max_send;
 extern enum protocol_types Protocol;
+extern const struct generic_mapping file_generic_mapping;
 
 static char *nttrans_realloc(char **ptr, size_t size)
 {
@@ -739,6 +740,10 @@ static NTSTATUS set_sd(files_struct *fsp, uint8 *data, uint32 sd_len,
                security_info_sent &= ~DACL_SECURITY_INFORMATION;
        }
 
+       /* Convert all the generic bits. */
+       security_acl_map_generic(psd->dacl, &file_generic_mapping);
+       security_acl_map_generic(psd->sacl, &file_generic_mapping);
+
        status = SMB_VFS_FSET_NT_ACL(fsp, security_info_sent, psd);
 
        TALLOC_FREE(psd);
index 71191475b365572ce212b106babc8bc07653f772..8727e80d5f740353f4d5900e31bd35d1efb4114c 100644 (file)
@@ -2608,9 +2608,7 @@ NTSTATUS create_file_unixpath(connection_struct *conn,
            && (create_disposition != FILE_CREATE)
            && (share_access & FILE_SHARE_DELETE)
            && (access_mask & DELETE_ACCESS)
-           && (((dos_mode(conn, fname, &sbuf) & FILE_ATTRIBUTE_READONLY)
-                && !lp_delete_readonly(SNUM(conn)))
-               || !can_delete_file_in_directory(conn, fname))) {
+           && (!can_delete_file_in_directory(conn, fname))) {
                status = NT_STATUS_ACCESS_DENIED;
                goto fail;
        }
@@ -2766,6 +2764,10 @@ NTSTATUS create_file_unixpath(connection_struct *conn,
 
                fsp->access_mask = FILE_GENERIC_ALL;
 
+               /* Convert all the generic bits. */
+               security_acl_map_generic(sd->dacl, &file_generic_mapping);
+               security_acl_map_generic(sd->sacl, &file_generic_mapping);
+
                status = SMB_VFS_FSET_NT_ACL(fsp, sec_info_sent, sd);
 
                fsp->access_mask = saved_access_mask;
index 7479aea0762d3144424d69306a6890698658bbe4..4e35e9deaabd342b3a2d1d5c6814acfdb12c838e 100644 (file)
@@ -890,13 +890,12 @@ static bool nt4_compatible_acls(void)
  not get. Deny entries are implicit on get with ace->perms = 0.
 ****************************************************************************/
 
-static SEC_ACCESS map_canon_ace_perms(int snum,
+static uint32_t map_canon_ace_perms(int snum,
                                enum security_ace_type *pacl_type,
                                mode_t perms,
                                bool directory_ace)
 {
-       SEC_ACCESS sa;
-       uint32 nt_mask = 0;
+       uint32_t nt_mask = 0;
 
        *pacl_type = SEC_ACE_TYPE_ACCESS_ALLOWED;
 
@@ -935,8 +934,7 @@ static SEC_ACCESS map_canon_ace_perms(int snum,
        DEBUG(10,("map_canon_ace_perms: Mapped (UNIX) %x to (NT) %x\n",
                        (unsigned int)perms, (unsigned int)nt_mask ));
 
-       init_sec_access(&sa,nt_mask);
-       return sa;
+       return nt_mask;
 }
 
 /****************************************************************************
@@ -988,7 +986,7 @@ static mode_t map_nt_perms( uint32 *mask, int type)
  Unpack a SEC_DESC into a UNIX owner and group.
 ****************************************************************************/
 
-NTSTATUS unpack_nt_owners(int snum, uid_t *puser, gid_t *pgrp, uint32 security_info_sent, SEC_DESC *psd)
+NTSTATUS unpack_nt_owners(int snum, uid_t *puser, gid_t *pgrp, uint32 security_info_sent, const SEC_DESC *psd)
 {
        DOM_SID owner_sid;
        DOM_SID grp_sid;
@@ -1329,11 +1327,13 @@ static void check_owning_objs(canon_ace *ace, DOM_SID *pfile_owner_sid, DOM_SID
  Unpack a SEC_DESC into two canonical ace lists.
 ****************************************************************************/
 
-static bool create_canon_ace_lists(files_struct *fsp, SMB_STRUCT_STAT *pst,
-                                                       DOM_SID *pfile_owner_sid,
-                                                       DOM_SID *pfile_grp_sid,
-                                                       canon_ace **ppfile_ace, canon_ace **ppdir_ace,
-                                                       SEC_ACL *dacl)
+static bool create_canon_ace_lists(files_struct *fsp,
+                                       SMB_STRUCT_STAT *pst,
+                                       DOM_SID *pfile_owner_sid,
+                                       DOM_SID *pfile_grp_sid,
+                                       canon_ace **ppfile_ace,
+                                       canon_ace **ppdir_ace,
+                                       const SEC_ACL *dacl)
 {
        bool all_aces_are_inherit_only = (fsp->is_directory ? True : False);
        canon_ace *file_ace = NULL;
@@ -2016,12 +2016,14 @@ static mode_t create_default_mode(files_struct *fsp, bool interitable_mode)
  succeeding.
 ****************************************************************************/
 
-static bool unpack_canon_ace(files_struct *fsp, 
-                                                       SMB_STRUCT_STAT *pst,
-                                                       DOM_SID *pfile_owner_sid,
-                                                       DOM_SID *pfile_grp_sid,
-                                                       canon_ace **ppfile_ace, canon_ace **ppdir_ace,
-                                                       uint32 security_info_sent, SEC_DESC *psd)
+static bool unpack_canon_ace(files_struct *fsp,
+                               SMB_STRUCT_STAT *pst,
+                               DOM_SID *pfile_owner_sid,
+                               DOM_SID *pfile_grp_sid,
+                               canon_ace **ppfile_ace,
+                               canon_ace **ppdir_ace,
+                               uint32 security_info_sent,
+                               const SEC_DESC *psd)
 {
        canon_ace *file_ace = NULL;
        canon_ace *dir_ace = NULL;
@@ -2958,9 +2960,7 @@ static NTSTATUS posix_get_nt_acl_common(struct connection_struct *conn,
                         */
 
                        for (ace = file_ace; ace != NULL; ace = ace->next) {
-                               SEC_ACCESS acc;
-
-                               acc = map_canon_ace_perms(SNUM(conn),
+                               uint32_t acc = map_canon_ace_perms(SNUM(conn),
                                                &nt_acl_type,
                                                ace->perms,
                                                S_ISDIR(sbuf->st_mode));
@@ -2975,19 +2975,14 @@ static NTSTATUS posix_get_nt_acl_common(struct connection_struct *conn,
                        /* The User must have access to a profile share - even
                         * if we can't map the SID. */
                        if (lp_profile_acls(SNUM(conn))) {
-                               SEC_ACCESS acc;
-
-                               init_sec_access(&acc,FILE_GENERIC_ALL);
                                init_sec_ace(&nt_ace_list[num_aces++],
                                                &global_sid_Builtin_Users,
                                                SEC_ACE_TYPE_ACCESS_ALLOWED,
-                                               acc, 0);
+                                               FILE_GENERIC_ALL, 0);
                        }
 
                        for (ace = dir_ace; ace != NULL; ace = ace->next) {
-                               SEC_ACCESS acc;
-
-                               acc = map_canon_ace_perms(SNUM(conn),
+                               uint32_t acc = map_canon_ace_perms(SNUM(conn),
                                                &nt_acl_type,
                                                ace->perms,
                                                S_ISDIR(sbuf->st_mode));
@@ -3005,10 +3000,7 @@ static NTSTATUS posix_get_nt_acl_common(struct connection_struct *conn,
                        /* The User must have access to a profile share - even
                         * if we can't map the SID. */
                        if (lp_profile_acls(SNUM(conn))) {
-                               SEC_ACCESS acc;
-
-                               init_sec_access(&acc,FILE_GENERIC_ALL);
-                               init_sec_ace(&nt_ace_list[num_aces++], &global_sid_Builtin_Users, SEC_ACE_TYPE_ACCESS_ALLOWED, acc,
+                               init_sec_ace(&nt_ace_list[num_aces++], &global_sid_Builtin_Users, SEC_ACE_TYPE_ACCESS_ALLOWED, FILE_GENERIC_ALL,
                                                SEC_ACE_FLAG_OBJECT_INHERIT|SEC_ACE_FLAG_CONTAINER_INHERIT|
                                                SEC_ACE_FLAG_INHERIT_ONLY|0);
                        }
@@ -3223,26 +3215,26 @@ int try_chown(connection_struct *conn, const char *fname, uid_t uid, gid_t gid)
  Take care of parent ACL inheritance.
 ****************************************************************************/
 
-static NTSTATUS append_parent_acl(files_struct *fsp,
-                               SMB_STRUCT_STAT *psbuf,
-                               SEC_DESC *psd,
+NTSTATUS append_parent_acl(files_struct *fsp,
+                               const SEC_DESC *pcsd,
                                SEC_DESC **pp_new_sd)
 {
        SEC_DESC *parent_sd = NULL;
        files_struct *parent_fsp = NULL;
-       TALLOC_CTX *mem_ctx = talloc_parent(psd);
+       TALLOC_CTX *mem_ctx = talloc_tos();
        char *parent_name = NULL;
        SEC_ACE *new_ace = NULL;
-       unsigned int num_aces = psd->dacl->num_aces;
+       unsigned int num_aces = pcsd->dacl->num_aces;
        SMB_STRUCT_STAT sbuf;
        NTSTATUS status;
        int info;
        unsigned int i, j;
-       bool is_dacl_protected = (psd->type & SE_DESC_DACL_PROTECTED);
+       SEC_DESC *psd = dup_sec_desc(talloc_tos(), pcsd);
+       bool is_dacl_protected = (pcsd->type & SE_DESC_DACL_PROTECTED);
 
        ZERO_STRUCT(sbuf);
 
-       if (mem_ctx == NULL) {
+       if (psd == NULL) {
                return NT_STATUS_NO_MEMORY;
        }
 
@@ -3398,11 +3390,6 @@ static NTSTATUS append_parent_acl(files_struct *fsp,
                        parent_name));
        }
 
-       /* This sucks. psd should be const and we should
-        * be doing a deep-copy here. We're getting away
-        * with is as we know parent_sd is talloced off
-        * talloc_tos() as well as psd. JRA. */
-
        psd->dacl->aces = new_ace;
        psd->dacl->num_aces = i;
        psd->type &= ~(SE_DESC_DACL_AUTO_INHERITED|
@@ -3418,7 +3405,7 @@ static NTSTATUS append_parent_acl(files_struct *fsp,
  This should be the only external function needed for the UNIX style set ACL.
 ****************************************************************************/
 
-NTSTATUS set_nt_acl(files_struct *fsp, uint32 security_info_sent, SEC_DESC *psd)
+NTSTATUS set_nt_acl(files_struct *fsp, uint32 security_info_sent, const SEC_DESC *psd)
 {
        connection_struct *conn = fsp->conn;
        uid_t user = (uid_t)-1;
@@ -3529,10 +3516,12 @@ NTSTATUS set_nt_acl(files_struct *fsp, uint32 security_info_sent, SEC_DESC *psd)
                              SE_DESC_DACL_AUTO_INHERIT_REQ))==
                        (SE_DESC_DACL_AUTO_INHERITED|
                         SE_DESC_DACL_AUTO_INHERIT_REQ) ) {
-               status = append_parent_acl(fsp, &sbuf, psd, &psd);
+               SEC_DESC *new_sd = NULL;
+               status = append_parent_acl(fsp, psd, &new_sd);
                if (!NT_STATUS_IS_OK(status)) {
                        return status;
                }
+               psd = new_sd;
        }
 
        acl_perms = unpack_canon_ace( fsp, &sbuf, &file_owner_sid, &file_grp_sid,
index b2d19e11e38850cb2701b044a784d42d26a1c5f1..32629fd3929191e9aa74d6b9a0266fac49dfdd4a 100644 (file)
@@ -706,7 +706,7 @@ The timeout is in milliseconds
 ****************************************************************************/
 
 static NTSTATUS receive_message_or_smb(TALLOC_CTX *mem_ctx, char **buffer,
-                                      size_t *buffer_len, int timeout,
+                                      size_t *buffer_len,
                                       size_t *p_unread, bool *p_encrypted)
 {
        fd_set r_fds, w_fds;
@@ -720,13 +720,8 @@ static NTSTATUS receive_message_or_smb(TALLOC_CTX *mem_ctx, char **buffer,
 
  again:
 
-       if (timeout >= 0) {
-               to.tv_sec = timeout / 1000;
-               to.tv_usec = (timeout % 1000) * 1000;
-       } else {
-               to.tv_sec = SMBD_SELECT_TIMEOUT;
-               to.tv_usec = 0;
-       }
+       to.tv_sec = SMBD_SELECT_TIMEOUT;
+       to.tv_usec = 0;
 
        /*
         * Note that this call must be before processing any SMB
@@ -869,7 +864,7 @@ static NTSTATUS receive_message_or_smb(TALLOC_CTX *mem_ctx, char **buffer,
 
        /* Did we timeout ? */
        if (selrtn == 0) {
-               return NT_STATUS_IO_TIMEOUT;
+               goto again;
        }
 
        /*
@@ -1836,23 +1831,6 @@ void chain_reply(struct smb_request *req)
        return;
 }
 
-/****************************************************************************
- Setup the needed select timeout in milliseconds.
-****************************************************************************/
-
-static int setup_select_timeout(void)
-{
-       int select_timeout;
-
-       select_timeout = SMBD_SELECT_TIMEOUT*1000;
-
-       if (print_notify_messages_pending()) {
-               select_timeout = MIN(select_timeout, 1000);
-       }
-
-       return select_timeout;
-}
-
 /****************************************************************************
  Check if services need reloading.
 ****************************************************************************/
@@ -1906,114 +1884,19 @@ void check_reload(time_t t)
        }
 }
 
-/****************************************************************************
- Process any timeout housekeeping. Return False if the caller should exit.
-****************************************************************************/
-
-static void timeout_processing(int *select_timeout,
-                              time_t *last_timeout_processing_time)
-{
-       time_t t;
-
-       *last_timeout_processing_time = t = time(NULL);
-
-       /* become root again if waiting */
-       change_to_root_user();
-
-       /* check if we need to reload services */
-       check_reload(t);
-
-       if(global_machine_password_needs_changing && 
-                       /* for ADS we need to do a regular ADS password change, not a domain
-                                       password change */
-                       lp_security() == SEC_DOMAIN) {
-
-               unsigned char trust_passwd_hash[16];
-               time_t lct;
-               void *lock;
-
-               /*
-                * We're in domain level security, and the code that
-                * read the machine password flagged that the machine
-                * password needs changing.
-                */
-
-               /*
-                * First, open the machine password file with an exclusive lock.
-                */
-
-               lock = secrets_get_trust_account_lock(NULL, lp_workgroup());
-
-               if (lock == NULL) {
-                       DEBUG(0,("process: unable to lock the machine account password for \
-machine %s in domain %s.\n", global_myname(), lp_workgroup() ));
-                       return;
-               }
-
-               if(!secrets_fetch_trust_account_password(lp_workgroup(), trust_passwd_hash, &lct, NULL)) {
-                       DEBUG(0,("process: unable to read the machine account password for \
-machine %s in domain %s.\n", global_myname(), lp_workgroup()));
-                       TALLOC_FREE(lock);
-                       return;
-               }
-
-               /*
-                * Make sure someone else hasn't already done this.
-                */
-
-               if(t < lct + lp_machine_password_timeout()) {
-                       global_machine_password_needs_changing = False;
-                       TALLOC_FREE(lock);
-                       return;
-               }
-
-               /* always just contact the PDC here */
-    
-               change_trust_account_password( lp_workgroup(), NULL);
-               global_machine_password_needs_changing = False;
-               TALLOC_FREE(lock);
-       }
-
-       /* update printer queue caches if necessary */
-  
-       update_monitored_printq_cache();
-  
-       /*
-        * Now we are root, check if the log files need pruning.
-        * Force a log file check.
-        */
-       force_check_log_size();
-       check_log_size();
-
-       /* Send any queued printer notify message to interested smbd's. */
-
-       print_notify_send_messages(smbd_messaging_context(), 0);
-
-       /*
-        * Modify the select timeout depending upon
-        * what we have remaining in our queues.
-        */
-
-       *select_timeout = setup_select_timeout();
-
-       return;
-}
-
 /****************************************************************************
  Process commands from the client
 ****************************************************************************/
 
 void smbd_process(void)
 {
-       time_t last_timeout_processing_time = time(NULL);
        unsigned int num_smbs = 0;
        size_t unread_bytes = 0;
 
        max_recv = MIN(lp_maxxmit(),BUFFER_SIZE);
 
        while (True) {
-               int select_timeout = setup_select_timeout();
-               int num_echos;
+               NTSTATUS status;
                char *inbuf = NULL;
                size_t inbuf_len = 0;
                bool encrypted = false;
@@ -2021,82 +1904,24 @@ void smbd_process(void)
 
                errno = 0;
 
-               /* Did someone ask for immediate checks on things like blocking locks ? */
-               if (select_timeout == 0) {
-                       timeout_processing(&select_timeout,
-                                          &last_timeout_processing_time);
-                       num_smbs = 0; /* Reset smb counter. */
-               }
-
                run_events(smbd_event_context(), 0, NULL, NULL);
 
-               while (True) {
-                       NTSTATUS status;
-
-                       status = receive_message_or_smb(
-                               talloc_tos(), &inbuf, &inbuf_len,
-                               select_timeout, &unread_bytes, &encrypted);
-
-                       if (NT_STATUS_IS_OK(status)) {
-                               break;
-                       }
-
-                       if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT)) {
-                               timeout_processing(
-                                       &select_timeout,
-                                       &last_timeout_processing_time);
-                               continue;
-                       }
+               status = receive_message_or_smb(
+                       talloc_tos(), &inbuf, &inbuf_len,
+                       &unread_bytes, &encrypted);
 
+               if (!NT_STATUS_IS_OK(status)) {
                        DEBUG(3, ("receive_message_or_smb failed: %s, "
                                  "exiting\n", nt_errstr(status)));
                        return;
-
-                       num_smbs = 0; /* Reset smb counter. */
                }
 
-
-               /*
-                * Ensure we do timeout processing if the SMB we just got was
-                * only an echo request. This allows us to set the select
-                * timeout in 'receive_message_or_smb()' to any value we like
-                * without worrying that the client will send echo requests
-                * faster than the select timeout, thus starving out the
-                * essential processing (change notify, blocking locks) that
-                * the timeout code does. JRA.
-                */
-               num_echos = smb_echo_count;
-
                process_smb(inbuf, inbuf_len, unread_bytes, encrypted);
 
                TALLOC_FREE(inbuf);
 
-               if (smb_echo_count != num_echos) {
-                       timeout_processing(&select_timeout,
-                                          &last_timeout_processing_time);
-                       num_smbs = 0; /* Reset smb counter. */
-               }
-
                num_smbs++;
 
-               /*
-                * If we are getting smb requests in a constant stream
-                * with no echos, make sure we attempt timeout processing
-                * every select_timeout milliseconds - but only check for this
-                * every 200 smb requests.
-                */
-               
-               if ((num_smbs % 200) == 0) {
-                       time_t new_check_time = time(NULL);
-                       if(new_check_time - last_timeout_processing_time >= (select_timeout/1000)) {
-                               timeout_processing(
-                                       &select_timeout,
-                                       &last_timeout_processing_time);
-                               num_smbs = 0; /* Reset smb counter. */
-                               last_timeout_processing_time = new_check_time; /* Reset time. */
-                       }
-               }
-
                /* The timeout_processing function isn't run nearly
                   often enough to implement 'max log size' without
                   overrunning the size of the file by many megabytes.
index 6933533672e1e180693236ecae3243c19c3c975e..48403073f73222f5750abe3c141e5ba7f67aa59b 100644 (file)
@@ -29,7 +29,6 @@
 /* look in server.c for some explanation of these variables */
 extern enum protocol_types Protocol;
 extern int max_recv;
-unsigned int smb_echo_count = 0;
 extern uint32 global_client_caps;
 
 extern bool global_encrypted_passwords_negotiated;
@@ -340,8 +339,7 @@ bool check_fsp_open(connection_struct *conn, struct smb_request *req,
 }
 
 /****************************************************************************
- Check if we have a correct fsp pointing to a file. Replacement for the
- CHECK_FSP macro.
+ Check if we have a correct fsp pointing to a file.
 ****************************************************************************/
 
 bool check_fsp(connection_struct *conn, struct smb_request *req,
@@ -4273,7 +4271,7 @@ void reply_close(struct smb_request *req)
        fsp = file_fsp(SVAL(req->inbuf,smb_vwv0));
 
        /*
-        * We can only use CHECK_FSP if we know it's not a directory.
+        * We can only use check_fsp if we know it's not a directory.
         */
 
        if(!fsp || (fsp->conn != conn) || (fsp->vuid != req->vuid)) {
@@ -4611,8 +4609,6 @@ void reply_echo(struct smb_request *req)
 
        TALLOC_FREE(req->outbuf);
 
-       smb_echo_count++;
-
        END_PROFILE(SMBecho);
        return;
 }
@@ -5583,10 +5579,10 @@ NTSTATUS rename_internals_fsp(connection_struct *conn,
                DEBUG(3,("rename_internals_fsp: succeeded doing rename on %s -> %s\n",
                        fsp->fsp_name,newname));
 
-               rename_open_files(conn, lck, newname);
-
                notify_rename(conn, fsp->is_directory, fsp->fsp_name, newname);
 
+               rename_open_files(conn, lck, newname);
+
                /*
                 * A rename acts as a new file create w.r.t. allowing an initial delete
                 * on close, probably because in Windows there is a new handle to the
index 53116f3d98ea016173d0b28c8e49d2fef3df5e33..69a483e4fca894e97cf056d3b13093212a3e1bbf 100644 (file)
@@ -1067,6 +1067,30 @@ static bool deadtime_fn(const struct timeval *now, void *private_data)
        return True;
 }
 
+/*
+ * Do the recurring log file and smb.conf reload checks.
+ */
+
+static bool housekeeping_fn(const struct timeval *now, void *private_data)
+{
+       change_to_root_user();
+
+       /* update printer queue caches if necessary */
+       update_monitored_printq_cache();
+
+       /* check if we need to reload services */
+       check_reload(time(NULL));
+
+       /* Change machine password if neccessary. */
+       attempt_machine_password_change();
+
+        /*
+        * Force a log file check.
+        */
+        force_check_log_size();
+        check_log_size();
+       return true;
+}
 
 /****************************************************************************
  main program.
@@ -1426,6 +1450,13 @@ extern void build_options(bool screen);
                exit(1);
        }
 
+       if (!(event_add_idle(smbd_event_context(), NULL,
+                            timeval_set(SMBD_SELECT_TIMEOUT, 0),
+                            "housekeeping", housekeeping_fn, NULL))) {
+               DEBUG(0, ("Could not add housekeeping event\n"));
+               exit(1);
+       }
+
 #ifdef CLUSTER_SUPPORT
 
        if (lp_clustering()) {
index 1ef4c152a3db90a2865fbe0cdb9fec1f5c13e865..627374cb96bb82162a7f31f01849479ad8fb52f3 100644 (file)
@@ -56,11 +56,11 @@ static int net_ads_cldap_netlogon(struct net_context *c, ADS_STRUCT *ads)
 
        d_printf("Response Type: ");
        switch (reply.command) {
-       case SAMLOGON_AD_UNK_R:
-               d_printf("SAMLOGON\n");
+       case LOGON_SAM_LOGON_USER_UNKNOWN_EX:
+               d_printf("LOGON_SAM_LOGON_USER_UNKNOWN_EX\n");
                break;
-       case SAMLOGON_AD_R:
-               d_printf("SAMLOGON_USER\n");
+       case LOGON_SAM_LOGON_RESPONSE_EX:
+               d_printf("LOGON_SAM_LOGON_RESPONSE_EX\n");
                break;
        default:
                d_printf("0x%x\n", reply.command);
index 14d45e2b0fcf4b9a6596fa55cf7ce065a88f3e39..4e617a196888c277fca2adc65fa3780e0bff029a 100644 (file)
@@ -145,14 +145,14 @@ error:
 int get_my_ip_address( struct sockaddr_storage **pp_ss )
 
 {
-       struct iface_struct nics[MAX_INTERFACES];
        int i, n;
        struct sockaddr_storage *list = NULL;
        int count = 0;
 
-       /* find the first non-loopback address from our list of interfaces */
+       /* Honor the configured list of interfaces to register */
 
-       n = get_interfaces(nics, MAX_INTERFACES);
+       load_interfaces();
+       n = iface_count();
 
        if (n <= 0) {
                return -1;
@@ -163,19 +163,17 @@ int get_my_ip_address( struct sockaddr_storage **pp_ss )
        }
 
        for ( i=0; i<n; i++ ) {
-               if (is_loopback_addr(&nics[i].ip)) {
+               const struct sockaddr_storage *nic_sa_storage = NULL;
+
+               if ((nic_sa_storage = iface_n_sockaddr_storage(i)) == NULL)
+                       continue;
+
+               /* Don't register loopback addresses */
+               if (is_loopback_addr(nic_sa_storage)) {
                        continue;
                }
-#if defined(HAVE_IPV6)
-               if ((nics[i].ip.ss_family == AF_INET6)) {
-                       memcpy(&list[count++], &nics[i].ip,
-                              sizeof(struct sockaddr_storage));
-               } else
-#endif
-               if (nics[i].ip.ss_family == AF_INET) {
-                       memcpy(&list[count++], &nics[i].ip,
-                              sizeof(struct sockaddr_storage));
-               }
+
+               memcpy(&list[count++], nic_sa_storage, sizeof(struct sockaddr_storage));
        }
        *pp_ss = list;
 
index 1e355e54a3e720a2b779ca5f17510f87a25a9640..ee4388f1577980c826b6c99cccfd1f8c567645d4 100644 (file)
@@ -471,6 +471,8 @@ int net_run_function(struct net_context *c, int argc, const char **argv,
                      const char *whoami, struct functable *table);
 void net_display_usage_from_functable(struct functable *table);
 
+const char *net_share_type_str(int num_type);
+
 /* The following definitions come from utils/netlookup.c  */
 
 NTSTATUS net_lookup_name_from_sid(struct net_context *c,
index 883524dc2df247f9e767b925fd11169699b6f55e..32f4dd31b4b853c1e273c892320c0ab70f191801 100644 (file)
 #define ERRMSG_BOTH_SERVER_IPADDRESS    "\nTarget server and IP address both "\
   "specified. Do not set both at the same time.  The target IP address was used\n"
 
-const char *share_type[] = {
-  "Disk",
-  "Print",
-  "Dev",
-  "IPC"
-};
-
 static int errmsg_not_implemented(void)
 {
        d_printf("\nNot implemented\n");
@@ -201,7 +194,7 @@ static void long_share_fn(const char *share_name, uint32 type,
                          const char *comment, void *state)
 {
        d_printf("%-12s %-8.8s %-50s\n",
-                share_name, share_type[type], comment);
+                share_name, net_share_type_str(type), comment);
 }
 
 static void share_fn(const char *share_name, uint32 type,
@@ -388,7 +381,7 @@ static void display_conns_func(uint16 conn_id, uint16 conn_type, uint16 opens,
                               const char *username, const char *netname)
 {
        d_printf("%-14.14s %-8.8s %5d\n",
-                netname, share_type[conn_type], opens);
+                netname, net_share_type_str(conn_type), opens);
 }
 
 static int rap_session_info(struct net_context *c, int argc, const char **argv)
index a849ec4c10b35ec5f89a4fd10940288c99ef7ca2..0e91144d339d218e69c60d280d5d9fc3db42969b 100644 (file)
@@ -26,8 +26,6 @@
 static int net_mode_share;
 static bool sync_files(struct copy_clistate *cp_clistate, const char *mask);
 
-extern const char *share_type[];
-
 /**
  * @file net_rpc.c
  *
@@ -2876,7 +2874,7 @@ static void display_share_info_1(struct net_context *c,
        if (c->opt_long_list_entries) {
                d_printf("%-12s %-8.8s %-50s\n",
                         r->shi1_netname,
-                        share_type[r->shi1_type & ~(STYPE_TEMPORARY|STYPE_HIDDEN)],
+                        net_share_type_str(r->shi1_type & ~(STYPE_TEMPORARY|STYPE_HIDDEN)),
                         r->shi1_remark);
        } else {
                d_printf("%s\n", r->shi1_netname);
index 88850d29df125849db31ea04115f33429fcaacd6..fbb3c24b03452e78e92e92f5dabb0c275440eb8e 100644 (file)
@@ -2,6 +2,7 @@
  *  Unix SMB/CIFS implementation.
  *  Helper routines for net
  *  Copyright (C) Volker Lendecke 2006
+ *  Copyright (C) Kai Blin 2008
  *
  *  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
@@ -595,3 +596,14 @@ void net_display_usage_from_functable(struct functable *table)
                d_printf("%s\n", table[i].usage);
        }
 }
+
+const char *net_share_type_str(int num_type)
+{
+       switch(num_type) {
+               case 0: return "Disk";
+               case 1: return "Print";
+               case 2: return "Dev";
+               case 3: return "IPC";
+               default: return "Unknown";
+       }
+}
index 46f9ecdc7df4578935f8805e7d5d2bf795e69401..3ad949a6d325ced8607c546fdd80abd870b51513 100644 (file)
@@ -153,7 +153,7 @@ static bool parse_ace(SEC_ACE *ace, const char *orig_str)
        unsigned int aflags = 0;
        unsigned int amask = 0;
        DOM_SID sid;
-       SEC_ACCESS mask;
+       uint32_t mask;
        const struct perm_value *v;
        char *str = SMB_STRDUP(orig_str);
        TALLOC_CTX *frame = talloc_stackframe();
index d488ce2187ab2283dfd1a20a3f88586d7c1283c6..eda8732c8914ef290ab113271fdd8a78b4575f08 100644 (file)
@@ -275,7 +275,7 @@ static bool parse_ace(struct cli_state *cli, SEC_ACE *ace,
        unsigned int aflags = 0;
        unsigned int amask = 0;
        DOM_SID sid;
-       SEC_ACCESS mask;
+       uint32_t mask;
        const struct perm_value *v;
        char *str = SMB_STRDUP(orig_str);
        TALLOC_CTX *frame = talloc_stackframe();
index 527db2d805330597ad2e4ca27fedccf820a53a86..4370d49523a7cf59d721c9450fa880ab2a7f4d30 100644 (file)
@@ -329,9 +329,12 @@ rameter is ignored when using CUPS libraries.\n",
        cname = poptGetArg(pc);
        caddr = poptGetArg(pc);
 
+       poptFreeContext(pc);
+
        if ( cname && ! caddr ) {
                printf ( "ERROR: You must specify both a machine name and an IP address.\n" );
-               return(1);
+               ret = 1;
+               goto done;
        }
 
        if (new_local_machine) {
@@ -346,7 +349,8 @@ rameter is ignored when using CUPS libraries.\n",
 
        if (!lp_load_with_registry_shares(config_file,False,True,False,True)) {
                fprintf(stderr,"Error loading services.\n");
-               return(1);
+               ret = 1;
+               goto done;
        }
 
        fprintf(stderr,"Loaded services file OK.\n");
@@ -393,13 +397,15 @@ rameter is ignored when using CUPS libraries.\n",
                                 (s=lp_servicenumber(section_name)) == -1) {
                                        fprintf(stderr,"Unknown section %s\n",
                                                section_name);
-                                       return(1);
+                                       ret = 1;
+                                       goto done;
                        }
                        if (parameter_name) {
                                if (!dump_a_parameter( s, parameter_name, stdout, isGlobal)) {
                                        fprintf(stderr,"Parameter %s unknown for section %s\n",
                                                parameter_name, section_name);
-                                       return(1);
+                                       ret = 1;
+                                       goto done;
                                }
                        } else {
                                if (isGlobal == True)
@@ -407,7 +413,7 @@ rameter is ignored when using CUPS libraries.\n",
                                else
                                        lp_dump_one(stdout, show_defaults, s);
                        }
-                       return(ret);
+                       goto done;
                }
 
                lp_dump(stdout, show_defaults, lp_numservices());
@@ -428,7 +434,10 @@ rameter is ignored when using CUPS libraries.\n",
                        }
                }
        }
+
+done:
        TALLOC_FREE(frame);
-       return(ret);
+       gfree_loadparm();
+       return ret;
 }
 
index ce24c7cddd480dd71f10c128834ded9264bd3d66..e684a075c25228762bdccf994dfdebdca84a32b1 100644 (file)
@@ -43,9 +43,10 @@ static void initPid2Machine (void)
 {
        /* show machine name rather PID on table "Open Files"? */
        if (PID_or_Machine) {
-               PIDMAP *p;
+               PIDMAP *p, *next;
 
-               for (p = pidmap; p != NULL; ) {
+               for (p = pidmap; p != NULL; p = next) {
+                       next = p->next;
                        DLIST_REMOVE(pidmap, p);
                        SAFE_FREE(p->machine);
                        SAFE_FREE(p);
index ab31ccef7a4af59bb4d7947a950820cb3bb1f83b..6851503cc8b7c647d5ea9625647a276e21d44bf1 100644 (file)
@@ -49,6 +49,12 @@ static NTSTATUS dc_add_domain(const char *domain)
        NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
        struct dc_info *dc = NULL;
 
+       if (!domain) {
+               return NT_STATUS_INVALID_PARAMETER;
+       }
+
+       DEBUG(10,("dc_add_domain: Attempting to add domain %s\n", domain));
+
        /* Check for duplicates */
 
        dc = dc_list_head();
@@ -73,6 +79,8 @@ static NTSTATUS dc_add_domain(const char *domain)
 
        nt_status = NT_STATUS_OK;
 
+       DEBUG(5,("dc_add_domain: Successfully added %s\n", domain));
+
 done:
        if (!NT_STATUS_IS_OK(nt_status)) {
                talloc_destroy(dc);
index 77eeee406b01dc03ec24ce67bcd6347c2cac9ed5..7723b3e0153fb490363db30042b49a5bac243cfc 100644 (file)
@@ -389,6 +389,24 @@ done:
                status = ads_do_search(c->conn, search_base,
                                       scope, expr, attrs, msg);
                if (ADS_ERR_OK(status)) {
+                       if (DEBUGLEVEL >= 10) {
+                               LDAPMessage *e = NULL;
+
+                               int n = ads_count_replies(c->conn, *msg);
+
+                               DEBUG(10,("cell_do_search: Located %d entries\n", n));
+
+                               for (e=ads_first_entry(c->conn, *msg);
+                                    e!=NULL;
+                                    e = ads_next_entry(c->conn, e))
+                               {
+                                       char *dn = ads_get_dn(c->conn, e);
+
+                                       DEBUGADD(10,("   dn: %s\n", dn ? dn : "<NULL>"));
+                                       SAFE_FREE(dn);
+                               }
+                       }
+
                        return status;
                }
 
index 3066db6f3b1e720c40b9efbe58f43207b5fd80c2..8bde963c608160397c8d5010bac0955c94441bed 100644 (file)
@@ -94,12 +94,11 @@ static NTSTATUS idmap_tdb2_open_db(void)
 */
 static NTSTATUS idmap_tdb2_alloc_load(void)
 {
-       const char *range;
        uid_t low_uid = 0;
        uid_t high_uid = 0;
        gid_t low_gid = 0;
        gid_t high_gid = 0;
-       uint32 low_id, high_id;
+       uint32 low_id;
 
        /* see if a idmap script is configured */
        idmap_tdb2_state.idmap_script = lp_parm_const_string(-1, "idmap",
@@ -187,6 +186,10 @@ static NTSTATUS idmap_tdb2_allocate_id(struct unixid *xid)
        uint32_t high_hwm;
        uint32_t hwm;
        int res;
+       NTSTATUS status;
+
+       status = idmap_tdb2_open_db();
+       NT_STATUS_NOT_OK_RETURN(status);
 
        /* Get current high water mark */
        switch (xid->type) {
@@ -264,6 +267,10 @@ static NTSTATUS idmap_tdb2_get_hwm(struct unixid *xid)
        const char *hwmtype;
        uint32_t hwm;
        uint32_t high_hwm;
+       NTSTATUS status;
+
+       status = idmap_tdb2_open_db();
+       NT_STATUS_NOT_OK_RETURN(status);
 
        /* Get current high water mark */
        switch (xid->type) {
@@ -451,6 +458,10 @@ static NTSTATUS idmap_tdb2_id_to_sid(struct idmap_tdb2_context *ctx, struct id_m
        NTSTATUS ret;
        TDB_DATA data;
        char *keystr;
+       NTSTATUS status;
+
+       status = idmap_tdb2_open_db();
+       NT_STATUS_NOT_OK_RETURN(status);
 
        if (!ctx || !map) {
                return NT_STATUS_INVALID_PARAMETER;
@@ -546,6 +557,10 @@ static NTSTATUS idmap_tdb2_sid_to_id(struct idmap_tdb2_context *ctx, struct id_m
        TDB_DATA data;
        char *keystr;
        unsigned long rec_id = 0;
+       NTSTATUS status;
+
+       status = idmap_tdb2_open_db();
+       NT_STATUS_NOT_OK_RETURN(status);
 
        if ((keystr = sid_string_talloc(ctx, map->sid)) == NULL) {
                DEBUG(0, ("Out of memory!\n"));
index b10a1a4ba940452b18bf515dd9af2ab794878ed1..9f876618be97aef0aa6c3ed07a0f9039e8120a5d 100644 (file)
@@ -121,7 +121,7 @@ backend:
                return NT_STATUS_NONE_MAPPED;
        }
 
-       idmap_cache_set_sid2uid(sid, gid);
+       idmap_cache_set_sid2gid(sid, gid);
 
        return NT_STATUS_OK;
 }
index 1600f05eb1ceb582cc2fc98622fb7571b34eaffb..aeb52d9b5aa3d648049edb990217846a94f4a388 100644 (file)
@@ -120,6 +120,10 @@ void async_request(TALLOC_CTX *mem_ctx, struct winbindd_child *child,
 
        SMB_ASSERT(continuation != NULL);
 
+       DEBUG(10, ("Sending request to child pid %d (domain=%s)\n",
+                  (int)child->pid,
+                  (child->domain != NULL) ? child->domain->name : "''"));
+
        state = TALLOC_P(mem_ctx, struct winbindd_async_request);
 
        if (state == NULL) {
@@ -296,6 +300,18 @@ static void schedule_async_request(struct winbindd_child *child)
                return;         /* Busy */
        }
 
+       /*
+        * This may be a reschedule, so we might
+        * have an existing timeout event pending on
+        * the first entry in the child->requests list
+        * (we only send one request at a time).
+        * Ensure we free it before we reschedule.
+        * Bug #5814, from hargagan <shargagan@novell.com>.
+        * JRA.
+        */
+
+       TALLOC_FREE(request->reply_timeout_event);
+
        if ((child->pid == 0) && (!fork_domain_child(child))) {
                /* fork_domain_child failed.
                   Cancel all outstanding requests */
@@ -491,6 +507,17 @@ void winbind_child_died(pid_t pid)
        child->event.flags = 0;
        child->pid = 0;
 
+       if (child->requests) {
+               /*
+                * schedule_async_request() will also
+                * clear this event but the call is
+                * idempotent so it doesn't hurt to
+                * cover all possible future code
+                * paths. JRA.
+                */
+               TALLOC_FREE(child->requests->reply_timeout_event);
+       }
+
        schedule_async_request(child);
 }
 
index b2a8bd7e3037ff2541a5f2ac62092328d7db05e1..b60d235f7083b2cfcf9d51f432c4653de0f3be86 100644 (file)
@@ -45,11 +45,15 @@ struct winbindd_child *locator_child(void)
 
 void winbindd_dsgetdcname(struct winbindd_cli_state *state)
 {
-       state->request.domain_name
-               [sizeof(state->request.domain_name)-1] = '\0';
+       state->request.data.dsgetdcname.domain_name
+               [sizeof(state->request.data.dsgetdcname.domain_name)-1] = '\0';
+       state->request.data.dsgetdcname.site_name
+               [sizeof(state->request.data.dsgetdcname.site_name)-1] = '\0';
+       state->request.data.dsgetdcname.domain_guid
+               [sizeof(state->request.data.dsgetdcname.domain_guid)-1] = '\0';
 
        DEBUG(3, ("[%5lu]: dsgetdcname for %s\n", (unsigned long)state->pid,
-                 state->request.domain_name));
+                 state->request.data.dsgetdcname.domain_name));
 
        sendto_child(state, locator_child());
 }
@@ -94,44 +98,59 @@ static uint32_t get_dsgetdc_flags(uint32_t wbc_flags)
        return ds_flags;
 }
 
-
 static enum winbindd_result dual_dsgetdcname(struct winbindd_domain *domain,
                                             struct winbindd_cli_state *state)
 {
        NTSTATUS result;
        struct netr_DsRGetDCNameInfo *info = NULL;
-       const char *dc = NULL;
        uint32_t ds_flags = 0;
+       struct GUID guid, *guid_ptr = NULL;
+       const char *guid_str = NULL;
 
-       state->request.domain_name
-               [sizeof(state->request.domain_name)-1] = '\0';
+       state->request.data.dsgetdcname.domain_name
+               [sizeof(state->request.data.dsgetdcname.domain_name)-1] = '\0';
+       state->request.data.dsgetdcname.site_name
+               [sizeof(state->request.data.dsgetdcname.site_name)-1] = '\0';
+       state->request.data.dsgetdcname.domain_guid
+               [sizeof(state->request.data.dsgetdcname.domain_guid)-1] = '\0';
 
        DEBUG(3, ("[%5lu]: dsgetdcname for %s\n", (unsigned long)state->pid,
-                 state->request.domain_name));
+                 state->request.data.dsgetdcname.domain_name));
 
        ds_flags = get_dsgetdc_flags(state->request.flags);
 
-       result = dsgetdcname(state->mem_ctx, winbind_messaging_context(),
-                            state->request.domain_name,
-                            NULL, NULL, ds_flags, &info);
-
-       if (!NT_STATUS_IS_OK(result)) {
-               return WINBINDD_ERROR;
+       result = GUID_from_string(state->request.data.dsgetdcname.domain_guid,
+                                 &guid);
+       if (NT_STATUS_IS_OK(result) && !GUID_all_zero(&guid)) {
+               guid_ptr = &guid;
        }
 
-       if (info->dc_address) {
-               dc = strip_hostname(info->dc_address);
-       }
+       result = dsgetdcname(state->mem_ctx,
+                            winbind_messaging_context(),
+                            state->request.data.dsgetdcname.domain_name,
+                            guid_ptr,
+                            state->request.data.dsgetdcname.site_name,
+                            ds_flags,
+                            &info);
 
-       if ((!dc || !is_ipaddress_v4(dc)) && info->dc_unc) {
-               dc = strip_hostname(info->dc_unc);
+       if (!NT_STATUS_IS_OK(result)) {
+               return WINBINDD_ERROR;
        }
 
-       if (!dc || !*dc) {
+       guid_str = GUID_string(state->mem_ctx, &info->domain_guid);
+       if (!guid_str) {
                return WINBINDD_ERROR;
        }
 
-       fstrcpy(state->response.data.dc_name, dc);
+       fstrcpy(state->response.data.dsgetdcname.dc_unc, info->dc_unc);
+       fstrcpy(state->response.data.dsgetdcname.dc_address, info->dc_address);
+       state->response.data.dsgetdcname.dc_address_type = info->dc_address_type;
+       fstrcpy(state->response.data.dsgetdcname.domain_guid, guid_str);
+       fstrcpy(state->response.data.dsgetdcname.domain_name, info->domain_name);
+       fstrcpy(state->response.data.dsgetdcname.forest_name, info->forest_name);
+       state->response.data.dsgetdcname.dc_flags = info->dc_flags;
+       fstrcpy(state->response.data.dsgetdcname.dc_site_name, info->dc_site_name);
+       fstrcpy(state->response.data.dsgetdcname.client_site_name, info->client_site_name);
 
        return WINBINDD_OK;
 }
index 5b5ca41a745322ae59a115b73016564e7801470a..fdfc8ed9d13dd3d076efa461d270da73d150b8ff 100644 (file)
@@ -111,7 +111,16 @@ static struct winbindd_domain *add_trusted_domain(const char *domain_name, const
        const char *alternative_name = NULL;
        char *idmap_config_option;
        const char *param;
+       const char **ignored_domains, **dom;
        
+       ignored_domains = lp_parm_string_list(-1, "winbind", "ignore domains", NULL);
+       for (dom=ignored_domains; dom && *dom; dom++) {
+               if (gen_fnmatch(*dom, domain_name) == 0) {
+                       DEBUG(2,("Ignoring domain '%s'\n", domain_name));
+                       return NULL;
+               }
+       }
+
        /* ignore alt_name if we are not in an AD domain */
        
        if ( (lp_security() == SEC_ADS) && alt_name && *alt_name) {
@@ -436,6 +445,10 @@ static void rescan_forest_root_trusts( void )
                                                &dom_list[i].sid );
                }
 
+               if (d == NULL) {
+                       continue;
+               }
+
                        DEBUG(10,("rescan_forest_root_trusts: Following trust path "
                          "for domain tree root %s (%s)\n",
                          d->name, d->alt_name ));
@@ -500,6 +513,10 @@ static void rescan_forest_trusts( void )
                                                        &cache_methods,
                                                        &dom_list[i].sid );
                        }
+
+                       if (d == NULL) {
+                               continue;
+                       }
                        
                        DEBUG(10,("Following trust path for domain %s (%s)\n",
                                  d->name, d->alt_name ));
@@ -1058,13 +1075,12 @@ void free_getent_state(struct getent_state *state)
        temp = state;
 
        while(temp != NULL) {
-               struct getent_state *next;
+               struct getent_state *next = temp->next;
 
                /* Free sam entries then list entry */
 
                SAFE_FREE(state->sam_entries);
                DLIST_REMOVE(state, state);
-               next = temp->next;
 
                SAFE_FREE(temp);
                temp = next;
similarity index 100%
rename from BUGS4.txt
rename to source4/BUGS
index 813f0cedd4ab85fee6c5c4e24bf7778a70db925e..cab82674d212d4ebdc9c4f713b326e784fa86aaf 100644 (file)
@@ -10,11 +10,11 @@ include mkconfig.mk
 
 pidldir := $(srcdir)/../pidl
 
-BASEDIR = $(prefix)
-TORTUREDIR = $(libdir)/torture
-SWATDIR = $(datadir)/swat
-SETUPDIR = $(datadir)/setup
-NCALRPCDIR = $(localstatedir)/ncalrpc
+basedir = $(prefix)
+torturedir = $(libdir)/torture
+swatdir = $(datadir)/swat
+setupdir = $(datadir)/setup
+ncalrpcdir = $(localstatedir)/ncalrpc
 
 BNLD = $(LD)
 BNLD_FLAGS = $(LDFLAGS) $(SYS_LDFLAGS)
@@ -97,7 +97,7 @@ ntvfssrcdir := ntvfs
 ntptrsrcdir := ntptr
 librpcsrcdir := librpc
 libclisrcdir := libcli
-libclinbtsrcdir := ../libcli
+libclinbtsrcdir := ../libcli/nbt
 pyscriptsrcdir := $(srcdir)/scripting/python
 kdcsrcdir := kdc
 ntp_signdsrcdir := ntp_signd
@@ -107,6 +107,15 @@ comsrcdir := $(srcdir)/lib/com
 
 include data.mk
 
+$(foreach SCRIPT,$(wildcard scripting/bin/*),$(eval $(call binary_install_template,$(SCRIPT))))
+
+$(DESTDIR)$(bindir)/%: scripting/bin/% installdirs
+       @mkdir -p $(@D)
+       @echo Installing $(@F) as $@
+       @if test -f $@; then echo -n ""; rm -f $@.old; mv $@ $@.old; fi
+       @cp $< $@
+       @chmod $(INSTALLPERMS) $@
+
 pythonmods:: $(PYTHON_PYS) $(PYTHON_SO)
 
 DEP_FILES = $(patsubst %.ho,%.hd,$(patsubst %.o,%.d,$(ALL_OBJS))) \
@@ -133,7 +142,7 @@ include $(srcdir)/static_deps.mk
 endif
 
 clean::
-       @find ../lib ../libcli  -name '*.o' -o -name '*.hd' | xargs rm -f
+       @find ../lib ../libcli -name '*.o' -o -name '*.hd' | xargs rm -f
 
 DEFAULT_HEADERS = $(srcdir)/lib/util/dlinklist.h \
                  $(srcdir)/version.h
@@ -155,7 +164,7 @@ testsuite:: bin/smbclient bin/cifsdd bin/smbtorture bin/nmblookup
 
 showlayout:: 
        @echo 'Samba will be installed into:'
-       @echo '  basedir:     $(BASEDIR)'
+       @echo '  basedir:     $(basedir)'
        @echo '  bindir:      $(bindir)'
        @echo '  sbindir:     $(sbindir)'
        @echo '  libdir:      $(libdir)'
@@ -166,10 +175,10 @@ showlayout::
        @echo '  piddir:      $(piddir)'
        @echo '  lockdir:     $(lockdir)'
        @echo '  logfilebase: $(logfilebase)'
-       @echo '  setupdir:    $(SETUPDIR)'
-       @echo '  swatdir:     $(SWATDIR)'
+       @echo '  setupdir:    $(setupdir)'
+       @echo '  swatdir:     $(swatdir)'
        @echo '  mandir:      $(mandir)'
-       @echo '  torturedir:  $(TORTUREDIR)'
+       @echo '  torturedir:  $(torturedir)'
        @echo '  datadir:     $(datadir)'
        @echo '  winbindd_socket_dir:  $(winbindd_socket_dir)'
        @echo '  ntp_signd_socket_dir:  $(ntp_signd_socket_dir)'
@@ -181,7 +190,7 @@ showflags::
 # The permissions to give the executables
 INSTALLPERMS = 0755
 
-install:: showlayout everything installbin installsbin installdat installswat installmisc \
+install:: showlayout everything installbin installsbin installdat installmisc \
              installlib installheader installpc installplugins
 
 # DESTDIR is used here to prevent packagers wasting their time
@@ -194,10 +203,10 @@ install:: showlayout everything installbin installsbin installdat installswat in
 
 installdirs::
        @$(SHELL) $(srcdir)/script/installdirs.sh \
-               $(DESTDIR)$(BASEDIR) \
+               $(DESTDIR)$(basedir) \
                $(DESTDIR)$(bindir) \
                $(DESTDIR)$(sbindir) \
-               $(DESTDIR)$(TORTUREDIR) \
+               $(DESTDIR)$(torturedir) \
                $(DESTDIR)$(libdir) \
                $(DESTDIR)$(modulesdir) \
                $(DESTDIR)$(mandir) \
@@ -211,7 +220,7 @@ installdirs::
                $(DESTDIR)$(logfilebase) \
                $(DESTDIR)$(privatedir)/tls \
                $(DESTDIR)$(includedir) \
-               $(DESTDIR)$(PKGCONFIGDIR) \
+               $(DESTDIR)$(pkgconfigdir) \
                $(DESTDIR)$(sysconfdir)
 
 installbin:: installdirs
@@ -228,24 +237,21 @@ installheader:: headers installdirs
 installdat:: installdirs
        @$(SHELL) $(srcdir)/script/installdat.sh $(DESTDIR)$(datadir) $(srcdir)
 
-installswat:: installdirs
-#SWAT has been disabled until further notice
-#      @$(SHELL) $(srcdir)/script/installswat.sh $(DESTDIR)$(SWATDIR) $(srcdir)
-
 installman:: manpages installdirs
        @$(SHELL) $(srcdir)/script/installman.sh $(DESTDIR)$(mandir) $(MANPAGES)
 
 installmisc:: installdirs
-       @$(SHELL) $(srcdir)/script/installmisc.sh $(srcdir) $(DESTDIR)$(SETUPDIR) $(DESTDIR)$(bindir)
+       @$(SHELL) $(srcdir)/script/installmisc.sh $(srcdir) $(DESTDIR)$(setupdir)
 
 installpc:: installdirs
-       @$(SHELL) $(srcdir)/script/installpc.sh $(builddir) $(DESTDIR)$(PKGCONFIGDIR) $(PC_FILES)
+       @$(SHELL) $(srcdir)/script/installpc.sh $(builddir) $(DESTDIR)$(pkgconfigdir) $(PC_FILES)
 
-uninstall:: uninstallbin uninstallman uninstallmisc uninstalllib uninstallheader \
-       uninstallplugins
+uninstall:: uninstallbin uninstallsbin uninstalldat uninstallmisc uninstalllib uninstallheader \
+                       uninstallman uninstallpc uninstallplugins
 
 uninstallmisc::
-       #FIXME
+       @echo "Removing MISC files"
+       @rm -rf $(DESTDIR)$(setupdir)/*
 
 $(DESTDIR)$(bindir)/%: bin/% installdirs
        @mkdir -p $(@D)
@@ -261,20 +267,30 @@ $(DESTDIR)$(sbindir)/%: bin/% installdirs
        @cp $< $@
        @chmod $(INSTALLPERMS) $@
 
+uninstalldat::
+       @echo "Removing DAT files"
+       @rm -fr $(DESTDIR)$(datadir)/*
+
 uninstallbin::
 
 uninstalllib::
+       @echo "Removing libraries"
        @$(SHELL) $(srcdir)/script/uninstalllib.sh $(DESTDIR)$(libdir) $(SHARED_LIBS)
-       #@$(SHELL) $(srcdir)/script/uninstalllib.sh $(DESTDIR)$(libdir) $(STATIC_LIBS) 
 
 uninstallheader::
-       @$(SHELL) $(srcdir)/script/uninstallheader.sh $(DESTDIR)$(includedir) $(PUBLIC_HEADERS)
+       @echo "Removing headers"
+       @rm -fr $(DESTDIR)$(includedir)/*
 
 uninstallman::
+       @echo "Removing manpages"
        @$(SHELL) $(srcdir)/script/uninstallman.sh $(DESTDIR)$(mandir) $(MANPAGES)
 
 uninstallplugins::
 
+uninstallpc::
+       @echo "Removing package configurations"
+       @cd $(DESTDIR)$(pkgconfigdir); rm -f $(notdir $(PC_FILES))
+
 config.status:
        @echo "config.status does not exist. Please run ./configure."
        @/bin/false
similarity index 100%
rename from NEWS4
rename to source4/NEWS
similarity index 98%
rename from TODO4
rename to source4/TODO
index 14df8a507a09f0ec4924d2482978aa7c37e4d481..5efebed1b3f342b38ef5a24b77cdf14b807936a9 100644 (file)
--- a/TODO4
@@ -1,7 +1,7 @@
-source/build/smb_build/TODO
-source/lib/registry/TODO
-source/lib/tdr/TODO
-source/pidl/TODO
+build/smb_build/TODO
+lib/registry/TODO
+lib/tdr/TODO
+pidl/TODO
 
 - seperate adminlog mechanism (as opposed to the current DEBUG log,
   which is not really aimed at administrators but more at developers)
index 06a7b8a38222b9a0f6dd6819db79b6f1c0fa0846..6f82de82fcd0a9ecfa082af4815b839b17fc298f 100644 (file)
@@ -110,7 +110,7 @@ static int gensec_sasl_get_password(sasl_conn_t *conn, void *context, int id,
 static int gensec_sasl_dispose(struct gensec_sasl_state *gensec_sasl_state)
 {
        sasl_dispose(&gensec_sasl_state->conn);
-       return 0;
+       return SASL_OK;
 }
 
 static NTSTATUS gensec_sasl_client_start(struct gensec_security *gensec_security)
index 0edb34d7403fc7d048314ac3d005bf2128bb202f..5d57383d2a853a3529ef4e16ceea4e90444d6778 100644 (file)
@@ -490,6 +490,7 @@ static NTSTATUS gensec_start(TALLOC_CTX *mem_ctx,
        NT_STATUS_HAVE_NO_MEMORY(*gensec_security);
 
        (*gensec_security)->ops = NULL;
+       (*gensec_security)->private_data = NULL;
 
        ZERO_STRUCT((*gensec_security)->target);
        ZERO_STRUCT((*gensec_security)->peer_addr);
@@ -525,6 +526,7 @@ _PUBLIC_ NTSTATUS gensec_subcontext_start(TALLOC_CTX *mem_ctx,
        (*gensec_security)->private_data = NULL;
 
        (*gensec_security)->subcontext = true;
+       (*gensec_security)->want_features = parent->want_features;
        (*gensec_security)->event_ctx = parent->event_ctx;
        (*gensec_security)->msg_ctx = parent->msg_ctx;
        (*gensec_security)->lp_ctx = parent->lp_ctx;
@@ -1015,7 +1017,11 @@ _PUBLIC_ NTSTATUS gensec_update_recv(struct gensec_update_request *req, TALLOC_C
 _PUBLIC_ void gensec_want_feature(struct gensec_security *gensec_security,
                         uint32_t feature) 
 {
-       gensec_security->want_features |= feature;
+       if (!gensec_security->ops || !gensec_security->ops->want_feature) {
+               gensec_security->want_features |= feature;
+               return;
+       }
+       gensec_security->ops->want_feature(gensec_security, feature);
 }
 
 /** 
index 84fc26d1271fc778a62efb96b79cba91d55a3125..0b31882ddd6865d95b4f2fc63018393ce5a3de2b 100644 (file)
@@ -133,6 +133,8 @@ struct gensec_security_ops {
        NTSTATUS (*session_key)(struct gensec_security *gensec_security, DATA_BLOB *session_key);
        NTSTATUS (*session_info)(struct gensec_security *gensec_security, 
                                 struct auth_session_info **session_info); 
+       void (*want_feature)(struct gensec_security *gensec_security,
+                                   uint32_t feature);
        bool (*have_feature)(struct gensec_security *gensec_security,
                                    uint32_t feature); 
        bool enabled;
index 0388b3caf69536b78337b8a581764aed8da27da2..64c21d0c3e195d08e01e581e4f47e7ac61f764b9 100644 (file)
@@ -44,7 +44,7 @@ struct ldb_context *schannel_db_connect(TALLOC_CTX *mem_ctx, struct event_contex
                "computerName: CASE_INSENSITIVE\n" \
                "flatname: CASE_INSENSITIVE\n";
 
-       path = smbd_tmp_path(mem_ctx, lp_ctx, "schannel.ldb");
+       path = private_path(mem_ctx, lp_ctx, "schannel.ldb");
        if (!path) {
                return NULL;
        }
index 1855e0583d71af366fadd22b4f150ff15fc42076..bf991616bd06eeccf77e9ae671eb296079f3b15d 100644 (file)
@@ -1094,6 +1094,20 @@ static NTSTATUS gensec_spnego_update(struct gensec_security *gensec_security, TA
        return NT_STATUS_INVALID_PARAMETER;
 }
 
+static void gensec_spnego_want_feature(struct gensec_security *gensec_security,
+                                      uint32_t feature)
+{
+       struct spnego_state *spnego_state = (struct spnego_state *)gensec_security->private_data;
+
+       if (!spnego_state || !spnego_state->sub_sec_security) {
+               gensec_security->want_features |= feature;
+               return;
+       }
+
+       gensec_want_feature(spnego_state->sub_sec_security,
+                           feature);
+}
+
 static bool gensec_spnego_have_feature(struct gensec_security *gensec_security,
                                       uint32_t feature) 
 {
@@ -1133,6 +1147,7 @@ static const struct gensec_security_ops gensec_spnego_security_ops = {
        .unwrap_packets   = gensec_spnego_unwrap_packets,
        .session_key      = gensec_spnego_session_key,
        .session_info     = gensec_spnego_session_info,
+       .want_feature     = gensec_spnego_want_feature,
        .have_feature     = gensec_spnego_have_feature,
        .enabled          = true,
        .priority         = GENSEC_SPNEGO
index 2579ab20cc4660ce588e19dbcc8a18bd868e2ffa..d54664fe66dfbd5bfd6e7a160a97357e23a5d1aa 100644 (file)
@@ -33,7 +33,7 @@
   This version is built to use a keyblock, rather than needing the
   original password.
 */
int kerberos_kinit_keyblock_cc(krb5_context ctx, krb5_ccache cc, 
krb5_error_code kerberos_kinit_keyblock_cc(krb5_context ctx, krb5_ccache cc, 
                                krb5_principal principal, krb5_keyblock *keyblock,
                                time_t *expire_time, time_t *kdc_time)
 {
@@ -77,7 +77,7 @@
   simulate a kinit, putting the tgt in the given credentials cache. 
   Orignally by remus@snapserver.com
 */
int kerberos_kinit_password_cc(krb5_context ctx, krb5_ccache cc, 
krb5_error_code kerberos_kinit_password_cc(krb5_context ctx, krb5_ccache cc, 
                                krb5_principal principal, const char *password, 
                                time_t *expire_time, time_t *kdc_time)
 {
index 9002715065aa23a809b9f5c706a321fda27dc91e..0567565d33987962bc84a0d119d0c3ab0c28cf35 100644 (file)
@@ -32,7 +32,7 @@ struct principal_container {
        krb5_principal principal;
 };
 
-static int free_principal(struct principal_container *pc)
+static krb5_error_code free_principal(struct principal_container *pc)
 {
        /* current heimdal - 0.6.3, which we need anyway, fixes segfaults here */
        krb5_free_principal(pc->smb_krb5_context->krb5_context, pc->principal);
@@ -241,19 +241,17 @@ static krb5_error_code salt_principal_from_credentials(TALLOC_CTX *parent_ctx,
        return 0;
 }
 
-static int free_keytab(struct keytab_container *ktc)
+static krb5_error_code free_keytab(struct keytab_container *ktc)
 {
-       krb5_kt_close(ktc->smb_krb5_context->krb5_context, ktc->keytab);
-
-       return 0;
+       return krb5_kt_close(ktc->smb_krb5_context->krb5_context, ktc->keytab);
 }
 
-int smb_krb5_open_keytab(TALLOC_CTX *mem_ctx,
+krb5_error_code smb_krb5_open_keytab(TALLOC_CTX *mem_ctx,
                         struct smb_krb5_context *smb_krb5_context, 
                         const char *keytab_name, struct keytab_container **ktc) 
 {
        krb5_keytab keytab;
-       int ret;
+       krb5_error_code ret;
        ret = krb5_kt_resolve(smb_krb5_context->krb5_context, keytab_name, &keytab);
        if (ret) {
                DEBUG(1,("failed to open krb5 keytab: %s\n", 
@@ -339,7 +337,7 @@ static krb5_error_code keytab_add_keys(TALLOC_CTX *parent_ctx,
        return 0;
 }
 
-static int create_keytab(TALLOC_CTX *parent_ctx,
+static krb5_error_code create_keytab(TALLOC_CTX *parent_ctx,
                         struct cli_credentials *machine_account,
                         struct smb_krb5_context *smb_krb5_context,
                         const char **enctype_strings,
@@ -603,7 +601,7 @@ static krb5_error_code remove_old_entries(TALLOC_CTX *parent_ctx,
        return ret;
 }
 
-int smb_krb5_update_keytab(TALLOC_CTX *parent_ctx,
+krb5_error_code smb_krb5_update_keytab(TALLOC_CTX *parent_ctx,
                           struct cli_credentials *machine_account,
                           struct smb_krb5_context *smb_krb5_context,
                           const char **enctype_strings,
@@ -635,7 +633,7 @@ int smb_krb5_update_keytab(TALLOC_CTX *parent_ctx,
        return ret;
 }
 
-int smb_krb5_create_memory_keytab(TALLOC_CTX *parent_ctx,
+krb5_error_code smb_krb5_create_memory_keytab(TALLOC_CTX *parent_ctx,
                                           struct cli_credentials *machine_account,
                                           struct smb_krb5_context *smb_krb5_context,
                                           const char **enctype_strings,
index 82e42a4560853a5d7f7ee3eacb605efcd6240484..90b542c4c46553c8a0d19b7791c6099ae50bc8d8 100644 (file)
@@ -49,13 +49,13 @@ struct smb_krb5_socket {
        krb5_krbhst_info *hi;
 };
 
-static int smb_krb5_context_destroy_1(struct smb_krb5_context *ctx)
+static krb5_error_code smb_krb5_context_destroy_1(struct smb_krb5_context *ctx)
 {
        krb5_free_context(ctx->krb5_context); 
        return 0;
 }
 
-static int smb_krb5_context_destroy_2(struct smb_krb5_context *ctx)
+static krb5_error_code smb_krb5_context_destroy_2(struct smb_krb5_context *ctx)
 {
        /* Otherwise krb5_free_context will try and close what we have already free()ed */
        krb5_set_warn_dest(ctx->krb5_context, NULL);
index bb8773e75e536677d91aaa8937c153d82e8108ba..539ae6aa80a1e9181cf3974dda437012415cc502 100644 (file)
@@ -80,6 +80,7 @@ static NTSTATUS server_get_challenge(struct auth_method_context *ctx, TALLOC_CTX
        io.in.workgroup = ""; /* only used with SPNEGO, disabled above */
 
        io.in.options = smb_options;
+       lp_smbcli_session_options(ctx->auth_ctx->lp_ctx, &io.in.session_options);
 
        status = smb_composite_connect(&io, mem_ctx, lp_resolve_context(ctx->auth_ctx->lp_ctx),
                                       ctx->auth_ctx->event_ctx);
index a56c5a223871923a5318e6248969801bb3af3ead..9984712caf81ce6130446cfa53d98c14776d0f27 100755 (executable)
@@ -2,6 +2,18 @@
 
 # Run this script to build samba from git.
 
+while true; do
+    case $1 in
+       (--version-file)
+           VERSION_FILE=$2
+           shift 2
+           ;;
+       (*)
+           break
+           ;;
+    esac
+done
+
 ## insert all possible names (only works with
 ## autoconf 2.x)
 TESTAUTOHEADER="autoheader autoheader-2.53 autoheader2.50 autoheader259 autoheader253"
@@ -48,7 +60,7 @@ if test "$AUTOCONFFOUND" = "0" -o "$AUTOHEADERFOUND" = "0"; then
 fi
 
 echo "$0: running script/mkversion.sh"
-./script/mkversion.sh || exit 1
+./script/mkversion.sh $VERSION_FILE || exit 1
 
 rm -rf autom4te*.cache
 rm -f configure include/config_tmp.h*
index 51d5daa913d4149a0d06992f50d94d69b2f78ce1..666dd3b0ae7fdd5c975a1ffc359936e98cb660ad 100644 (file)
@@ -23,13 +23,13 @@ winbindd_socket_dir="${localstatedir}/run/winbindd"
 winbindd_privileged_socket_dir="${localstatedir}/lib/winbindd_privileged"
 ntp_signd_socket_dir="${localstatedir}/run/ntp_signd"
 
-# Check to prevent installing directly under /usr without the FHS
-AS_IF([test ${prefix} == /usr],[
-    AC_MSG_ERROR([Don't install directly under "/usr" without using the FHS option (--with-fhs). This could lead to file loss!])
-])
+AC_ARG_ENABLE(fhs, 
+[AS_HELP_STRING([--enable-fhs],[Use FHS-compliant paths (default=no)])],
+[fhs=$enableval],
+[fhs=no]
+)
 
-AC_ARG_WITH(fhs, 
-[AS_HELP_STRING([--with-fhs],[Use FHS-compliant paths (default=no)])],
+if test x$fhs = xyes; then
     lockdir="${localstatedir}/lib/samba"
     piddir="${localstatedir}/run/samba"
     logfilebase="${localstatedir}/log/samba"
@@ -41,7 +41,12 @@ AC_ARG_WITH(fhs,
     ntp_signd_socket_dir="${localstatedir}/run/samba/ntp_signd"
     winbindd_socket_dir="${localstatedir}/run/samba/winbindd"
     winbindd_privileged_socket_dir="${localstatedir}/lib/samba/winbindd_privileged"
-)
+else
+       # Check to prevent installing directly under /usr without the FHS
+       AS_IF([test $prefix == /usr || $prefix == /usr/local],[
+               AC_MSG_ERROR([Don't install directly under "/usr" or "/usr/local" without using the FHS option (--enable-fhs). This could lead to file loss!])
+       ])
+fi
 
 #################################################
 # set private directory location
index 310fb564e0fc5068d8845bf158d09e20d44fcac9..240f2b1dc23d3cb5ba9ea5d94e2ed8d9ac3bf2db 100644 (file)
@@ -127,6 +127,7 @@ static NTSTATUS cldapd_startup_interfaces(struct cldapd_server *cldapd, struct l
        int num_interfaces;
        TALLOC_CTX *tmp_ctx = talloc_new(cldapd);
        NTSTATUS status;
+       int i;
 
        num_interfaces = iface_count(ifaces);
 
@@ -135,14 +136,14 @@ static NTSTATUS cldapd_startup_interfaces(struct cldapd_server *cldapd, struct l
        if (!lp_bind_interfaces_only(lp_ctx)) {
                status = cldapd_add_socket(cldapd, lp_ctx, "0.0.0.0");
                NT_STATUS_NOT_OK_RETURN(status);
-       } else {
-               int i;
-
-               for (i=0; i<num_interfaces; i++) {
-                       const char *address = talloc_strdup(tmp_ctx, iface_n_ip(ifaces, i));
-                       status = cldapd_add_socket(cldapd, lp_ctx, address);
-                       NT_STATUS_NOT_OK_RETURN(status);
-               }
+       }
+
+       /* now we have to also listen on the specific interfaces,
+          so that replies always come from the right IP */
+       for (i=0; i<num_interfaces; i++) {
+               const char *address = talloc_strdup(tmp_ctx, iface_n_ip(ifaces, i));
+               status = cldapd_add_socket(cldapd, lp_ctx, address);
+               NT_STATUS_NOT_OK_RETURN(status);
        }
 
        talloc_free(tmp_ctx);
index 7dccd81fad2a17d6195dd1a71402b4178fcaf6a4..1cb0d50d02befef0bc44d8d16d4ec5d941890c72 100644 (file)
@@ -301,7 +301,7 @@ NTSTATUS fill_netlogon_samlogon_response(struct ldb_context *sam_ctx,
                server_type |= NBT_SERVER_KDC;
        }
 
-       if (!ldb_dn_compare_base(ldb_get_root_basedn(sam_ctx), ldb_get_default_basedn(sam_ctx))) {
+       if (ldb_dn_compare(ldb_get_root_basedn(sam_ctx), ldb_get_default_basedn(sam_ctx)) == 0) {
                server_type |= NBT_SERVER_DS_DNS_FOREST;
        }
 
@@ -331,68 +331,68 @@ NTSTATUS fill_netlogon_samlogon_response(struct ldb_context *sam_ctx,
 
                /* could check if the user exists */
                if (user_known) {
-                       netlogon->nt5_ex.command      = LOGON_SAM_LOGON_RESPONSE_EX;
+                       netlogon->data.nt5_ex.command      = LOGON_SAM_LOGON_RESPONSE_EX;
                } else {
-                       netlogon->nt5_ex.command      = LOGON_SAM_LOGON_USER_UNKNOWN_EX;
+                       netlogon->data.nt5_ex.command      = LOGON_SAM_LOGON_USER_UNKNOWN_EX;
                }
-               netlogon->nt5_ex.server_type  = server_type;
-               netlogon->nt5_ex.domain_uuid  = domain_uuid;
-               netlogon->nt5_ex.forest       = realm;
-               netlogon->nt5_ex.dns_domain   = dns_domain;
-               netlogon->nt5_ex.pdc_dns_name = pdc_dns_name;
-               netlogon->nt5_ex.domain       = flatname;
-               netlogon->nt5_ex.pdc_name     = lp_netbios_name(lp_ctx);
-               netlogon->nt5_ex.user_name    = user;
-               netlogon->nt5_ex.server_site  = server_site;
-               netlogon->nt5_ex.client_site  = client_site;
+               netlogon->data.nt5_ex.server_type  = server_type;
+               netlogon->data.nt5_ex.domain_uuid  = domain_uuid;
+               netlogon->data.nt5_ex.forest       = realm;
+               netlogon->data.nt5_ex.dns_domain   = dns_domain;
+               netlogon->data.nt5_ex.pdc_dns_name = pdc_dns_name;
+               netlogon->data.nt5_ex.domain       = flatname;
+               netlogon->data.nt5_ex.pdc_name     = lp_netbios_name(lp_ctx);
+               netlogon->data.nt5_ex.user_name    = user;
+               netlogon->data.nt5_ex.server_site  = server_site;
+               netlogon->data.nt5_ex.client_site  = client_site;
 
                if (version & NETLOGON_NT_VERSION_5EX_WITH_IP) {
                        /* Clearly this needs to be fixed up for IPv6 */
                        extra_flags = NETLOGON_NT_VERSION_5EX_WITH_IP;
-                       netlogon->nt5_ex.sockaddr.sa_family    = 2;
-                       netlogon->nt5_ex.sockaddr.pdc_ip       = pdc_ip;
-                       netlogon->nt5_ex.sockaddr.remaining = data_blob_talloc_zero(mem_ctx, 8);
+                       netlogon->data.nt5_ex.sockaddr.sa_family    = 2;
+                       netlogon->data.nt5_ex.sockaddr.pdc_ip       = pdc_ip;
+                       netlogon->data.nt5_ex.sockaddr.remaining = data_blob_talloc_zero(mem_ctx, 8);
                }
-               netlogon->nt5_ex.nt_version   = NETLOGON_NT_VERSION_1|NETLOGON_NT_VERSION_5EX|extra_flags;
-               netlogon->nt5_ex.lmnt_token   = 0xFFFF;
-               netlogon->nt5_ex.lm20_token   = 0xFFFF;
+               netlogon->data.nt5_ex.nt_version   = NETLOGON_NT_VERSION_1|NETLOGON_NT_VERSION_5EX|extra_flags;
+               netlogon->data.nt5_ex.lmnt_token   = 0xFFFF;
+               netlogon->data.nt5_ex.lm20_token   = 0xFFFF;
 
        } else if (version & NETLOGON_NT_VERSION_5) {
                netlogon->ntver = NETLOGON_NT_VERSION_5;
 
                /* could check if the user exists */
                if (user_known) {
-                       netlogon->nt5.command      = LOGON_SAM_LOGON_RESPONSE;
+                       netlogon->data.nt5.command      = LOGON_SAM_LOGON_RESPONSE;
                } else {
-                       netlogon->nt5.command      = LOGON_SAM_LOGON_USER_UNKNOWN;
+                       netlogon->data.nt5.command      = LOGON_SAM_LOGON_USER_UNKNOWN;
                }
-               netlogon->nt5.pdc_name     = pdc_name;
-               netlogon->nt5.user_name    = user;
-               netlogon->nt5.domain_name  = flatname;
-               netlogon->nt5.domain_uuid  = domain_uuid;
-               netlogon->nt5.forest       = realm;
-               netlogon->nt5.dns_domain   = dns_domain;
-               netlogon->nt5.pdc_dns_name = pdc_dns_name;
-               netlogon->nt5.pdc_ip       = pdc_ip;
-               netlogon->nt5.server_type  = server_type;
-               netlogon->nt5.nt_version   = NETLOGON_NT_VERSION_1|NETLOGON_NT_VERSION_5;
-               netlogon->nt5.lmnt_token   = 0xFFFF;
-               netlogon->nt5.lm20_token   = 0xFFFF;
+               netlogon->data.nt5.pdc_name     = pdc_name;
+               netlogon->data.nt5.user_name    = user;
+               netlogon->data.nt5.domain_name  = flatname;
+               netlogon->data.nt5.domain_uuid  = domain_uuid;
+               netlogon->data.nt5.forest       = realm;
+               netlogon->data.nt5.dns_domain   = dns_domain;
+               netlogon->data.nt5.pdc_dns_name = pdc_dns_name;
+               netlogon->data.nt5.pdc_ip       = pdc_ip;
+               netlogon->data.nt5.server_type  = server_type;
+               netlogon->data.nt5.nt_version   = NETLOGON_NT_VERSION_1|NETLOGON_NT_VERSION_5;
+               netlogon->data.nt5.lmnt_token   = 0xFFFF;
+               netlogon->data.nt5.lm20_token   = 0xFFFF;
 
        } else /* (version & NETLOGON_NT_VERSION_1) and all other cases */ {
                netlogon->ntver = NETLOGON_NT_VERSION_1;
                /* could check if the user exists */
                if (user_known) {
-                       netlogon->nt4.command      = LOGON_SAM_LOGON_RESPONSE;
+                       netlogon->data.nt4.command      = LOGON_SAM_LOGON_RESPONSE;
                } else {
-                       netlogon->nt4.command      = LOGON_SAM_LOGON_USER_UNKNOWN;
+                       netlogon->data.nt4.command      = LOGON_SAM_LOGON_USER_UNKNOWN;
                }
-               netlogon->nt4.server      = pdc_name;
-               netlogon->nt4.user_name   = user;
-               netlogon->nt4.domain      = flatname;
-               netlogon->nt4.nt_version  = NETLOGON_NT_VERSION_1;
-               netlogon->nt4.lmnt_token  = 0xFFFF;
-               netlogon->nt4.lm20_token  = 0xFFFF;
+               netlogon->data.nt4.server      = pdc_name;
+               netlogon->data.nt4.user_name   = user;
+               netlogon->data.nt4.domain      = flatname;
+               netlogon->data.nt4.nt_version  = NETLOGON_NT_VERSION_1;
+               netlogon->data.nt4.lmnt_token  = 0xFFFF;
+               netlogon->data.nt4.lm20_token  = 0xFFFF;
        }
 
        return NT_STATUS_OK;
index 4ff71c086342225f14c0b9bbfacff53f1d819026..65786e67085172b2ff90a4a7f98295ed31ffa15c 100644 (file)
@@ -66,22 +66,19 @@ static void cldapd_rootdse_fill(struct cldapd_server *cldapd,
                attrs[i] = NULL;
        }
 
-       lreq = talloc(mem_ctx, struct ldb_request);
-       if (lreq == NULL) goto nomem;
-
        res = talloc_zero(mem_ctx, struct ldb_result);
        if (res == NULL) goto nomem;
 
-       lreq->operation = LDB_SEARCH;
-       lreq->op.search.base = basedn;
-       lreq->op.search.scope = scope;
-       lreq->op.search.tree = search->tree;
-       lreq->op.search.attrs = attrs;
-
-       lreq->controls = NULL;
+       ldb_ret = ldb_build_search_req_ex(&lreq, cldapd->samctx, mem_ctx,
+                                         basedn, scope,
+                                         search->tree, attrs,
+                                         NULL,
+                                         res, ldb_search_default_callback,
+                                         NULL);
 
-       lreq->context = res;
-       lreq->callback = ldb_search_default_callback;
+       if (ldb_ret != LDB_SUCCESS) {
+               goto reply;
+       }
 
        /* Copy the timeout from the incoming call */
        ldb_set_timeout(cldapd->samctx, lreq, search->timelimit);
index 141b165ad44808e68f61011137720593411afa16..5f07826d06eb7381ffcbc8759053163882731cf6 100644 (file)
@@ -357,7 +357,8 @@ static void print_transfer_stats(void)
 static struct dd_iohandle * open_file(struct resolve_context *resolve_ctx, 
                                      struct event_context *ev,
                                      const char * which, const char **ports,
-                                     struct smbcli_options *smb_options)
+                                     struct smbcli_options *smb_options,
+                                     struct smbcli_session_options *smb_session_options)
 {
        int                     options = 0;
        const char *            path = NULL;
@@ -379,13 +380,13 @@ static struct dd_iohandle * open_file(struct resolve_context *resolve_ctx,
                path = check_arg_pathname("if");
                handle = dd_open_path(resolve_ctx, ev, path, ports,
                                      check_arg_numeric("ibs"), options,
-                                     smb_options);
+                                     smb_options, smb_session_options);
        } else if (strcmp(which, "of") == 0) {
                options |= DD_WRITE;
                path = check_arg_pathname("of");
                handle = dd_open_path(resolve_ctx, ev, path, ports,
                                      check_arg_numeric("obs"), options,
-                                     smb_options);
+                                     smb_options, smb_session_options);
        } else {
                SMB_ASSERT(0);
                return(NULL);
@@ -412,12 +413,14 @@ static int copy_files(struct event_context *ev, struct loadparm_context *lp_ctx)
        struct dd_iohandle *    ofile;
 
        struct smbcli_options options;
+       struct smbcli_session_options session_options;
 
        ibs = check_arg_numeric("ibs");
        obs = check_arg_numeric("obs");
        count = check_arg_numeric("count");
 
        lp_smbcli_options(lp_ctx, &options);
+       lp_smbcli_session_options(lp_ctx, &session_options);
 
        /* Allocate IO buffer. We need more than the max IO size because we
         * could accumulate a remainder if ibs and obs don't match.
@@ -436,12 +439,14 @@ static int copy_files(struct event_context *ev, struct loadparm_context *lp_ctx)
                        (unsigned long long)iomax, options.max_xmit));
 
        if (!(ifile = open_file(lp_resolve_context(lp_ctx), ev, "if",
-                               lp_smb_ports(lp_ctx), &options))) {
+                               lp_smb_ports(lp_ctx), &options,
+                               &session_options))) {
                return(FILESYS_EXIT_CODE);
        }
 
        if (!(ofile = open_file(lp_resolve_context(lp_ctx), ev, "of",
-                               lp_smb_ports(lp_ctx), &options))) {
+                               lp_smb_ports(lp_ctx), &options,
+                               &session_options))) {
                return(FILESYS_EXIT_CODE);
        }
 
index 21a4ad488222048da96c650a219b3ab6533fb7e1..3195e4334f3bc4938fa97ad1bf6e4293465784f8 100644 (file)
@@ -89,6 +89,7 @@ struct dd_iohandle
 #define DD_OPLOCK              0x00000008
 
 struct smbcli_options;
+struct smbcli_session_options;
 struct event_context;
 
 struct dd_iohandle * dd_open_path(struct resolve_context *resolve_ctx, 
@@ -96,7 +97,8 @@ struct dd_iohandle * dd_open_path(struct resolve_context *resolve_ctx,
                                  const char * path,
                                  const char **ports,
                                uint64_t io_size, int options, 
-                               struct smbcli_options *smb_options);
+                               struct smbcli_options *smb_options,
+                               struct smbcli_session_options *smb_session_options);
 bool dd_fill_block(struct dd_iohandle * h, uint8_t * buf,
                uint64_t * buf_size, uint64_t need_size, uint64_t block_size);
 bool dd_flush_block(struct dd_iohandle * h, uint8_t * buf,
index 4297c300121ef6c4f57b379caa9005975619efb8..25194a621a82472db63e02fc7b60964978cee21e 100644 (file)
@@ -225,7 +225,8 @@ static struct smbcli_state * init_smb_session(struct resolve_context *resolve_ct
                                              const char * host,
                                              const char **ports,
                                              const char * share,
-                                             struct smbcli_options *options)
+                                             struct smbcli_options *options,
+                                             struct smbcli_session_options *session_options)
 {
        NTSTATUS                ret;
        struct smbcli_state *   cli = NULL;
@@ -236,7 +237,8 @@ static struct smbcli_state * init_smb_session(struct resolve_context *resolve_ct
        ret = smbcli_full_connection(NULL, &cli, host, ports, share,
                                     NULL /* devtype */,
                                     cmdline_credentials, resolve_ctx,
-                                    ev, options);
+                                    ev, options,
+                                    session_options);
 
        if (!NT_STATUS_IS_OK(ret)) {
                fprintf(stderr, "%s: connecting to //%s/%s: %s\n",
@@ -302,7 +304,8 @@ static struct dd_iohandle * open_cifs_handle(struct resolve_context *resolve_ctx
                                        const char * path,
                                        uint64_t io_size,
                                        int options,
-                                       struct smbcli_options *smb_options)
+                                       struct smbcli_options *smb_options,
+                                       struct smbcli_session_options *smb_session_options)
 {
        struct cifs_handle * smbh;
 
@@ -323,7 +326,7 @@ static struct dd_iohandle * open_cifs_handle(struct resolve_context *resolve_ctx
        smbh->h.io_seek = smb_seek_func;
 
        if ((smbh->cli = init_smb_session(resolve_ctx, ev, host, ports, share,
-                                         smb_options)) == NULL) {
+                                         smb_options, smb_session_options)) == NULL) {
                return(NULL);
        }
 
@@ -344,7 +347,8 @@ struct dd_iohandle * dd_open_path(struct resolve_context *resolve_ctx,
                                  const char **ports,
                                uint64_t io_size,
                                int options,
-                               struct smbcli_options *smb_options)
+                               struct smbcli_options *smb_options,
+                               struct smbcli_session_options *smb_session_options)
 {
        if (file_exist(path)) {
                return(open_fd_handle(path, io_size, options));
@@ -361,7 +365,8 @@ struct dd_iohandle * dd_open_path(struct resolve_context *resolve_ctx,
 
                        return(open_cifs_handle(resolve_ctx, ev, host, ports,
                                                share, remain,
-                                               io_size, options, smb_options));
+                                               io_size, options, smb_options,
+                                               smb_session_options));
                }
 
                return(open_fd_handle(path, io_size, options));
index e05e195372f2ca362d54b7e52321e2caf6a79861..266bd670250da182465ef41b04f58789c3920eb9 100644 (file)
@@ -3032,7 +3032,8 @@ static bool do_connect(struct smbclient_context *ctx,
                       const char *specified_server, const char **ports, 
                       const char *specified_share, 
                       struct cli_credentials *cred, 
-                      struct smbcli_options *options)
+                      struct smbcli_options *options,
+                      struct smbcli_session_options *session_options)
 {
        NTSTATUS status;
        char *server, *share;
@@ -3051,7 +3052,7 @@ static bool do_connect(struct smbclient_context *ctx,
        
        status = smbcli_full_connection(ctx, &ctx->cli, server, ports,
                                        share, NULL, cred, resolve_ctx, 
-                                       ev_ctx, options);
+                                       ev_ctx, options, session_options);
        if (!NT_STATUS_IS_OK(status)) {
                d_printf("Connection to \\\\%s\\%s failed - %s\n", 
                         server, share, nt_errstr(status));
@@ -3138,6 +3139,7 @@ static int do_message_op(const char *netbios_name, const char *desthost,
        struct smbclient_context *ctx;
        const char *cmdstr = NULL;
        struct smbcli_options smb_options;
+       struct smbcli_session_options smb_session_options;
 
        struct poptOption long_options[] = {
                POPT_AUTOHELP
@@ -3227,6 +3229,7 @@ static int do_message_op(const char *netbios_name, const char *desthost,
        poptFreeContext(pc);
 
        lp_smbcli_options(cmdline_lp_ctx, &smb_options);
+       lp_smbcli_session_options(cmdline_lp_ctx, &smb_session_options);
 
        ev_ctx = s4_event_context_init(talloc_autofree_context());
 
@@ -3255,7 +3258,7 @@ static int do_message_op(const char *netbios_name, const char *desthost,
        
        if (!do_connect(ctx, ev_ctx, lp_resolve_context(cmdline_lp_ctx),
                        desthost, lp_smb_ports(cmdline_lp_ctx), service,
-                       cmdline_credentials, &smb_options))
+                       cmdline_credentials, &smb_options, &smb_session_options))
                return 1;
 
        if (base_directory) 
index 9ab6c375f25d07174a4b3236a237fd4e36eb5177..37c9eaadc47b3c2f541a46e6c614ba5ed02e1577 100644 (file)
@@ -111,7 +111,8 @@ static void usr1_handler(int x)
 /***************************************************** 
 return a connection to a server
 *******************************************************/
-static struct smbcli_state *do_connection(const char *the_service, bool unicode, int maxprotocol)
+static struct smbcli_state *do_connection(const char *the_service, bool unicode, int maxprotocol,
+                                         struct smbcli_session_options session_options)
 {
        struct smbcli_state *c;
        struct nmb_name called, calling;
@@ -210,11 +211,12 @@ static struct smbcli_state *do_connection(const char *the_service, bool unicode,
        if (!smbcli_session_setup(c, username, 
                               password, strlen(password),
                               password, strlen(password),
-                              workgroup)) {
+                              workgroup, session_options)) {
                /* if a password was not supplied then try again with a
                        null username */
                if (password[0] || !username[0] ||
-                               !smbcli_session_setup(c, "", "", 0, "", 0, workgroup)) {
+                               !smbcli_session_setup(c, "", "", 0, "", 0, workgroup, 
+                                                     session_options)) {
                        DEBUG(0,("%d: session setup failed: %s\n",
                                sys_getpid(), smbcli_errstr(c)));
                        talloc_free(c);
@@ -329,6 +331,9 @@ static void send_fs_socket(struct loadparm_context *lp_ctx,
        int fd, closed = 0, res = 1;
        pid_t parentpid = getppid();
        struct smb_conn_opt conn_options;
+       struct smbcli_session_options session_options;
+
+       lp_smbcli_session_options(lp_ctx, &session_options);
 
        memset(&conn_options, 0, sizeof(conn_options));
 
@@ -409,7 +414,8 @@ static void send_fs_socket(struct loadparm_context *lp_ctx,
                        DEBUG(2,("mount.smbfs[%d]: got signal, getting new socket\n", sys_getpid()));
                        c = do_connection(the_service, 
                                          lp_unicode(lp_ctx), 
-                                         lp_cli_maxprotocol(lp_ctx));
+                                         lp_cli_maxprotocol(lp_ctx),
+                                         session_options);
                }
        }
 
@@ -430,14 +436,17 @@ static void init_mount(struct loadparm_context *lp_ctx)
        struct smbcli_state *c;
        char *args[20];
        int i, status;
+       struct smbcli_session_options session_options;
 
        if (realpath(mpoint, mount_point) == NULL) {
                fprintf(stderr, "Could not resolve mount point %s\n", mpoint);
                return;
        }
 
+       lp_smbcli_session_options(lp_ctx, &session_options);
 
-       c = do_connection(service, lp_unicode(lp_ctx), lp_cli_maxprotocol(lp_ctx));
+       c = do_connection(service, lp_unicode(lp_ctx), lp_cli_maxprotocol(lp_ctx),
+                         session_options);
        if (!c) {
                fprintf(stderr,"SMB connection failed\n");
                exit(1);
index fa2d8d99506c47437705bf18979cc2a8edbeaf06..611b8dd104bcf70f7de104354ed70c145c0fb52f 100644 (file)
@@ -46,7 +46,7 @@ SMB_EXT_LIB_FROM_PKGCONFIG(LIBTALLOC, talloc >= 1.2.0,
        ]
 )
 
-SMB_EXT_LIB_FROM_PKGCONFIG(LIBTDB, tdb >= 1.1.0,
+SMB_EXT_LIB_FROM_PKGCONFIG(LIBTDB, tdb >= 1.1.3,
        [],
        [
                m4_include(../lib/tdb/libtdb.m4)
index 7324d898a65f6c579aa4ae1044f81d69a586b789..ca87159c5889badf33194af9a43b9e61c609b679 100644 (file)
@@ -356,15 +356,7 @@ WERROR DsCrackNameOneName(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx,
        const char *result_filter = NULL;
        struct ldb_dn *name_dn = NULL;
 
-       struct smb_krb5_context *smb_krb5_context;
-       ret = smb_krb5_init_context(mem_ctx, 
-                                   ldb_get_event_context(sam_ctx),
-                                   (struct loadparm_context *)ldb_get_opaque(sam_ctx, "loadparm"), 
-                                   &smb_krb5_context);
-                               
-       if (ret) {
-               return WERR_NOMEM;
-       }
+       struct smb_krb5_context *smb_krb5_context = NULL;
 
        info1->status = DRSUAPI_DS_NAME_STATUS_RESOLVE_ERROR;
        info1->dns_domain_name = NULL;
@@ -380,6 +372,30 @@ WERROR DsCrackNameOneName(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx,
 
        /* here we need to set the domain_filter and/or the result_filter */
        switch (format_offered) {
+       case DRSUAPI_DS_NAME_FORMAT_UNKNOWN:
+       {
+               int i;
+               enum drsuapi_DsNameFormat formats[] = {
+                       DRSUAPI_DS_NAME_FORMAT_FQDN_1779, DRSUAPI_DS_NAME_FORMAT_USER_PRINCIPAL,
+                       DRSUAPI_DS_NAME_FORMAT_NT4_ACCOUNT, DRSUAPI_DS_NAME_FORMAT_CANONICAL,
+                       DRSUAPI_DS_NAME_FORMAT_GUID, DRSUAPI_DS_NAME_FORMAT_DISPLAY,
+                       DRSUAPI_DS_NAME_FORMAT_SERVICE_PRINCIPAL,
+                       DRSUAPI_DS_NAME_FORMAT_SID_OR_SID_HISTORY,
+                       DRSUAPI_DS_NAME_FORMAT_CANONICAL_EX
+               };
+               WERROR werr;
+               for (i=0; i < ARRAY_SIZE(formats); i++) {
+                       werr = DsCrackNameOneName(sam_ctx, mem_ctx, format_flags, formats[i], format_desired, name, info1);
+                       if (!W_ERROR_IS_OK(werr)) {
+                               return werr;
+                       }
+                       if (info1->status != DRSUAPI_DS_NAME_STATUS_NOT_FOUND) {
+                               return werr;
+                       }
+               }
+               return werr;
+       }
+
        case DRSUAPI_DS_NAME_FORMAT_CANONICAL:
        case DRSUAPI_DS_NAME_FORMAT_CANONICAL_EX:
        {
@@ -534,6 +550,16 @@ WERROR DsCrackNameOneName(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx,
        case DRSUAPI_DS_NAME_FORMAT_USER_PRINCIPAL: {
                krb5_principal principal;
                char *unparsed_name;
+
+               ret = smb_krb5_init_context(mem_ctx, 
+                                           ldb_get_event_context(sam_ctx),
+                                           (struct loadparm_context *)ldb_get_opaque(sam_ctx, "loadparm"), 
+                                           &smb_krb5_context);
+               
+               if (ret) {
+                       return WERR_NOMEM;
+               }
+
                ret = krb5_parse_name(smb_krb5_context->krb5_context, name, &principal);
                if (ret) {
                        info1->status = DRSUAPI_DS_NAME_STATUS_NOT_FOUND;
@@ -560,6 +586,16 @@ WERROR DsCrackNameOneName(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx,
                krb5_principal principal;
                char *unparsed_name_short;
                char *service;
+
+               ret = smb_krb5_init_context(mem_ctx, 
+                                           ldb_get_event_context(sam_ctx),
+                                           (struct loadparm_context *)ldb_get_opaque(sam_ctx, "loadparm"), 
+                                           &smb_krb5_context);
+               
+               if (ret) {
+                       return WERR_NOMEM;
+               }
+
                ret = krb5_parse_name(smb_krb5_context->krb5_context, name, &principal);
                if (ret == 0 && principal->name.name_string.len < 2) {
                        info1->status = DRSUAPI_DS_NAME_STATUS_NOT_FOUND;
@@ -797,7 +833,8 @@ static WERROR DsCrackNameOneFilter(struct ldb_context *sam_ctx, TALLOC_CTX *mem_
                                                   result_attrs,
                                                   NULL,
                                                   res,
-                                                  ldb_search_default_callback);
+                                                  ldb_search_default_callback,
+                                                  NULL);
                        if (ret == LDB_SUCCESS) {
                                struct ldb_search_options_control *search_options;
                                search_options = talloc(req, struct ldb_search_options_control);
@@ -812,8 +849,6 @@ static WERROR DsCrackNameOneFilter(struct ldb_context *sam_ctx, TALLOC_CTX *mem_
                                return WERR_OK;
                        }
                        
-                       ldb_set_timeout(sam_ctx, req, 0); /* use default timeout */
-                       
                        ret = ldb_request(sam_ctx, req);
                        
                        if (ret == LDB_SUCCESS) {
@@ -1266,7 +1301,7 @@ NTSTATUS crack_auto_name_to_nt4_name(TALLOC_CTX *mem_ctx,
                                     const char **nt4_domain,
                                     const char **nt4_account)
 {
-       uint32_t format_offered = DRSUAPI_DS_NAME_FORMAT_UKNOWN;
+       uint32_t format_offered = DRSUAPI_DS_NAME_FORMAT_UNKNOWN;
 
        /* Handle anonymous bind */
        if (!name || !*name) {
@@ -1283,6 +1318,8 @@ NTSTATUS crack_auto_name_to_nt4_name(TALLOC_CTX *mem_ctx,
                format_offered = DRSUAPI_DS_NAME_FORMAT_NT4_ACCOUNT;
        } else if (strchr_m(name, '/')) {
                format_offered = DRSUAPI_DS_NAME_FORMAT_CANONICAL;
+       } else {
+               return NT_STATUS_NO_SUCH_USER;
        }
 
        return crack_name_to_nt4_name(mem_ctx, ev_ctx, lp_ctx, format_offered, name, nt4_domain, nt4_account);
index 4e2c527fe9c31335590511f6cd6c8a4b3b7f2198..028df588d6bddb44fb874e773c156189a6e533c0 100644 (file)
@@ -1,7 +1,8 @@
 /* 
    ldb database library
 
-   Copyright (C) Amdrew Bartlett <abartlet@samba.org> 2007
+   Copyright (C) Andrew Bartlett <abartlet@samba.org> 2007
+   Copyright (C) Simo Sorce <idra@samba.org> 2008
    Copyright (C) Andrew Tridgell  2004
     
    This program is free software; you can redistribute it and/or modify
@@ -99,6 +100,7 @@ struct ldb_parse_tree *make_match_tree(struct ldb_module *module,
 struct anr_context {
        bool found_anr;
        struct ldb_module *module;
+       struct ldb_request *req;
 };
 
 /**
@@ -106,39 +108,35 @@ struct anr_context {
  * parse tree with an 'or' of all the anr attributes in the schema.  
  */
 
-typedef struct ldb_parse_tree *(*anr_parse_tree_callback_t)(TALLOC_CTX *mem_ctx,
-                                                          const struct ldb_val *match,
-                                                          void *context);
-
-
 /**
- * Callback function to do the heavy lifting for the for the parse tree walker 
+ * Callback function to do the heavy lifting for the parse tree walker
  */
-struct ldb_parse_tree *anr_replace_callback(TALLOC_CTX *mem_ctx,
-                                           const struct ldb_val *match,
-                                           void *context)
+static int anr_replace_value(struct anr_context *ac,
+                            TALLOC_CTX *mem_ctx,
+                            const struct ldb_val *match,
+                            struct ldb_parse_tree **ntree)
 {
        struct ldb_parse_tree *tree = NULL;
-       struct anr_context *anr_context = talloc_get_type(context, struct anr_context);
-       struct ldb_module *module = anr_context->module;
+       struct ldb_module *module = ac->module;
        struct ldb_parse_tree *match_tree;
-       uint8_t *p;
-       enum ldb_parse_op op;
        struct dsdb_attribute *cur;
        const struct dsdb_schema *schema = dsdb_get_schema(module->ldb);
+       uint8_t *p;
+       enum ldb_parse_op op;
+
        if (!schema) {
                ldb_asprintf_errstring(module->ldb, "no schema with which to construct anr filter");
-               return NULL;
+               return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       anr_context->found_anr = true;
+       ac->found_anr = true;
 
        if (match->length > 1 && match->data[0] == '=') {
-               DATA_BLOB *match2 = talloc(tree, DATA_BLOB);
+               DATA_BLOB *match2 = talloc(mem_ctx, DATA_BLOB);
                *match2 = data_blob_const(match->data+1, match->length - 1);
                if (match2 == NULL){
                        ldb_oom(module->ldb);
-                       return NULL;
+                       return LDB_ERR_OPERATIONS_ERROR;
                }
                match = match2;
                op = LDB_OP_EQUALITY;
@@ -154,7 +152,7 @@ struct ldb_parse_tree *anr_replace_callback(TALLOC_CTX *mem_ctx,
                        tree = make_parse_list(module, mem_ctx,  LDB_OP_OR, tree, match_tree);
                        if (tree == NULL) {
                                ldb_oom(module->ldb);
-                               return NULL;
+                               return LDB_ERR_OPERATIONS_ERROR;
                        }
                } else {
                        tree = match_tree;
@@ -173,7 +171,7 @@ struct ldb_parse_tree *anr_replace_callback(TALLOC_CTX *mem_ctx,
                DATA_BLOB *second_match = talloc(tree, DATA_BLOB);
                if (!first_match || !second_match) {
                        ldb_oom(module->ldb);
-                       return NULL;
+                       return LDB_ERR_OPERATIONS_ERROR;
                }
                *first_match = data_blob_const(match->data, p-match->data);
                *second_match = data_blob_const(p+1, match->length - (p-match->data) - 1);
@@ -183,26 +181,26 @@ struct ldb_parse_tree *anr_replace_callback(TALLOC_CTX *mem_ctx,
                match_tree_1 = make_match_tree(module, mem_ctx, op, "givenName", first_match);
                match_tree_2 = make_match_tree(module, mem_ctx, op, "sn", second_match);
 
-               first_split_filter = make_parse_list(module, context,  LDB_OP_AND, match_tree_1, match_tree_2);
+               first_split_filter = make_parse_list(module, ac,  LDB_OP_AND, match_tree_1, match_tree_2);
                if (first_split_filter == NULL){
                        ldb_oom(module->ldb);
-                       return NULL;
+                       return LDB_ERR_OPERATIONS_ERROR;
                }
                
                match_tree_1 = make_match_tree(module, mem_ctx, op, "sn", first_match);
                match_tree_2 = make_match_tree(module, mem_ctx, op, "givenName", second_match);
 
-               second_split_filter = make_parse_list(module, context,  LDB_OP_AND, match_tree_1, match_tree_2);
+               second_split_filter = make_parse_list(module, ac,  LDB_OP_AND, match_tree_1, match_tree_2);
                if (second_split_filter == NULL){
                        ldb_oom(module->ldb);
-                       return NULL;
+                       return LDB_ERR_OPERATIONS_ERROR;
                }
 
                split_filters = make_parse_list(module, mem_ctx,  LDB_OP_OR, 
                                                first_split_filter, second_split_filter);
                if (split_filters == NULL) {
                        ldb_oom(module->ldb);
-                       return NULL;
+                       return LDB_ERR_OPERATIONS_ERROR;
                }
 
                if (tree) {
@@ -212,38 +210,46 @@ struct ldb_parse_tree *anr_replace_callback(TALLOC_CTX *mem_ctx,
                        tree = split_filters;
                }
        }
-       return tree;
+       *ntree = tree;
+       return LDB_SUCCESS;
 }
 
 /*
   replace any occurances of an attribute with a new, generated attribute tree
 */
-struct ldb_parse_tree *anr_replace_subtrees(struct ldb_parse_tree *tree, 
-                                           const char *attr, 
-                                           anr_parse_tree_callback_t callback,
-                                           void *context)
+static int anr_replace_subtrees(struct anr_context *ac,
+                               struct ldb_parse_tree *tree,
+                               const char *attr,
+                               struct ldb_parse_tree **ntree)
 {
+       int ret;
        int i;
-       struct ldb_parse_tree *tmp;
 
        switch (tree->operation) {
        case LDB_OP_AND:
        case LDB_OP_OR:
                for (i=0;i<tree->u.list.num_elements;i++) {
-                       tmp = anr_replace_subtrees(tree->u.list.elements[i],
-                                                  attr, callback, context);
-                       if (tmp) tree->u.list.elements[i] = tmp;
+                       ret = anr_replace_subtrees(ac, tree->u.list.elements[i],
+                                                  attr, &tree->u.list.elements[i]);
+                       if (ret != LDB_SUCCESS) {
+                               return ret;
+                       }
+                       *ntree = tree;
                }
                break;
        case LDB_OP_NOT:
-               tmp = anr_replace_subtrees(tree->u.isnot.child, attr, callback, context);
-               if (tmp) tree->u.isnot.child = tmp;
+               ret = anr_replace_subtrees(ac, tree->u.isnot.child, attr, &tree->u.isnot.child);
+               if (ret != LDB_SUCCESS) {
+                       return ret;
+               }
+               *ntree = tree;
                break;
        case LDB_OP_EQUALITY:
                if (ldb_attr_cmp(tree->u.equality.attr, attr) == 0) {
-                       tmp = callback(tree, &tree->u.equality.value, 
-                                       context);
-                       if (tmp) tree = tmp;
+                       ret = anr_replace_value(ac, tree, &tree->u.equality.value, ntree);
+                       if (ret != LDB_SUCCESS) {
+                               return ret;
+                       }
                }
                break;
        case LDB_OP_SUBSTRING:
@@ -252,53 +258,97 @@ struct ldb_parse_tree *anr_replace_subtrees(struct ldb_parse_tree *tree,
                            tree->u.substring.end_with_wildcard == 1 && 
                            tree->u.substring.chunks[0] != NULL && 
                            tree->u.substring.chunks[1] == NULL) {
-                               tmp = callback(tree, tree->u.substring.chunks[0], context);
-                               if (tmp) tree = tmp;
+                               ret = anr_replace_value(ac, tree, tree->u.substring.chunks[0], ntree);
+                               if (ret != LDB_SUCCESS) {
+                                       return ret;
+                               }
                        }
                }
                break;
+       default:
+               break;
+       }
+
+       return LDB_SUCCESS;
+}
+
+static int anr_search_callback(struct ldb_request *req, struct ldb_reply *ares)
+{
+       struct anr_context *ac;
+
+       ac = talloc_get_type(req->context, struct anr_context);
+
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
+
+       switch (ares->type) {
+       case LDB_REPLY_ENTRY:
+               return ldb_module_send_entry(ac->req, ares->message);
+
+       case LDB_REPLY_REFERRAL:
+               return ldb_module_send_referral(ac->req, ares->referral);
+
+       case LDB_REPLY_DONE:
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, LDB_SUCCESS);
+
        }
-       return tree;
+       return LDB_SUCCESS;
 }
 
 /* search */
 static int anr_search(struct ldb_module *module, struct ldb_request *req)
 {
        struct ldb_parse_tree *anr_tree;
-       struct anr_context *context = talloc(req, struct anr_context);
-       if (!context) {
+       struct ldb_request *down_req;
+       struct anr_context *ac;
+       int ret;
+
+       ac = talloc(req, struct anr_context);
+       if (!ac) {
                ldb_oom(module->ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       context->module = module;
-       context->found_anr = false;
+       ac->module = module;
+       ac->req = req;
+       ac->found_anr = false;
 
 #if 0
        printf("oldanr : %s\n", ldb_filter_from_tree (0, req->op.search.tree));
 #endif
 
-       /* Yes, this is a problem with req->op.search.tree being const... */
-       anr_tree = anr_replace_subtrees(req->op.search.tree, "anr", anr_replace_callback, context);
-       if (!anr_tree) {
-               talloc_free(context);
+       ret = anr_replace_subtrees(ac, req->op.search.tree, "anr", &anr_tree);
+       if (ret != LDB_SUCCESS) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       if (context->found_anr) {
-               /* The above function modifies the tree if it finds "anr", so no
-                * point just setting this on the down_req */
-#if 0
-               printf("newtree: %s\n", ldb_filter_from_tree (0, anr_tree));
-#endif
-               req->op.search.tree = talloc_steal(req, anr_tree);
-       } else {
-               if (anr_tree != req->op.search.tree) {
-                       talloc_free(anr_tree);
-               }
-               talloc_free(context);
+       if (!ac->found_anr) {
+               talloc_free(ac);
+               return ldb_next_request(module, req);
        }
-       return ldb_next_request(module, req);
+
+       ret = ldb_build_search_req_ex(&down_req,
+                                       module->ldb, ac,
+                                       req->op.search.base,
+                                       req->op.search.scope,
+                                       anr_tree,
+                                       req->op.search.attrs,
+                                       req->controls,
+                                       ac, anr_search_callback,
+                                       req);
+       if (ret != LDB_SUCCESS) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+       talloc_steal(down_req, anr_tree);
+
+       return ldb_next_request(module, down_req);
 }
 
 _PUBLIC_ const struct ldb_module_ops ldb_anr_module_ops = {
index 84bf5e484352c635b9dd1791638e255128969eb6..88a8887056ed6c48e7aae3b48c7c3242df929412 100644 (file)
@@ -1,7 +1,7 @@
 /* 
    ldb database library
 
-   Copyright (C) Simo Sorce  2005
+   Copyright (C) Simo Sorce 2005-2008
 
      ** NOTE! The following LGPL license applies to the ldb
      ** library. This does NOT imply that all of Samba is released
@@ -95,7 +95,7 @@ static bool add_attrs(void *mem_ctx, char ***attrs, const char *attr)
        return true;
 }
 
-static bool inject_extended_dn(struct ldb_message *msg,
+static int inject_extended_dn(struct ldb_message *msg,
                                struct ldb_context *ldb,
                                int type,
                                bool remove_guid,
@@ -113,8 +113,9 @@ static bool inject_extended_dn(struct ldb_message *msg,
        guid_blob = ldb_msg_find_ldb_val(msg, "objectGUID");
        sid_blob = ldb_msg_find_ldb_val(msg, "objectSID");
 
-       if (!guid_blob)
-               return false;
+       if (!guid_blob) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
 
        switch (type) {
                case 0:
@@ -123,7 +124,7 @@ static bool inject_extended_dn(struct ldb_message *msg,
                                const char *lower_guid_hex = strlower_talloc(msg, data_blob_hex_string(msg, guid_blob));
                                const char *lower_sid_hex = strlower_talloc(msg, data_blob_hex_string(msg, sid_blob));
                                if (!lower_guid_hex || !lower_sid_hex) {
-                                       return false;
+                                       return LDB_ERR_OPERATIONS_ERROR;
                                }
                                new_dn = talloc_asprintf(msg, "<GUID=%s>;<SID=%s>;%s",
                                                         lower_guid_hex, 
@@ -132,7 +133,7 @@ static bool inject_extended_dn(struct ldb_message *msg,
                        } else {
                                const char *lower_guid_hex = strlower_talloc(msg, data_blob_hex_string(msg, guid_blob));
                                if (!lower_guid_hex) {
-                                       return false;
+                                       return LDB_ERR_OPERATIONS_ERROR;
                                }
                                new_dn = talloc_asprintf(msg, "<GUID=%s>;%s",
                                                         lower_guid_hex, 
@@ -151,8 +152,8 @@ static bool inject_extended_dn(struct ldb_message *msg,
                        if (sid) {
                                object_sid = dom_sid_string(msg, sid);
                                if (!object_sid)
-                                       return false;
-                               
+                                       return LDB_ERR_OPERATIONS_ERROR;
+
                        }
                        
                        /* Normal, sane format */
@@ -167,11 +168,11 @@ static bool inject_extended_dn(struct ldb_message *msg,
                        }
                        break;
                default:
-                       return false;
+                       return LDB_ERR_OPERATIONS_ERROR;
        }
 
        if (!new_dn) {
-               return false;
+               return LDB_ERR_OPERATIONS_ERROR;
        }
 
        if (remove_guid) {
@@ -184,50 +185,186 @@ static bool inject_extended_dn(struct ldb_message *msg,
 
        msg->dn = ldb_dn_new(msg, ldb, new_dn);
        if (! ldb_dn_validate(msg->dn))
-               return false;
+               return LDB_ERR_OPERATIONS_ERROR;
 
        val = ldb_msg_find_ldb_val(msg, "distinguishedName");
        if (val) {
                ldb_msg_remove_attr(msg, "distinguishedName");
                if (ldb_msg_add_steal_string(msg, "distinguishedName", new_dn))
-                       return false;
+                       return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       return true;
+       return LDB_SUCCESS;
 }
 
 /* search */
 struct extended_context {
 
        struct ldb_module *module;
-       void *up_context;
-       int (*up_callback)(struct ldb_context *, void *, struct ldb_reply *);
-
-       const char * const *attrs;
+       struct ldb_request *req;
+       struct ldb_control *control;
+       struct ldb_dn *basedn;
+       char *wellknown_object;
+       bool inject;
        bool remove_guid;
        bool remove_sid;
        int extended_type;
+       const char * const *cast_attrs;
 };
 
-static int extended_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares)
+static int extended_callback(struct ldb_request *req, struct ldb_reply *ares)
 {
        struct extended_context *ac;
+       int ret;
 
-       ac = talloc_get_type(context, struct extended_context);
+       ac = talloc_get_type(req->context, struct extended_context);
 
-       if (ares->type == LDB_REPLY_ENTRY) {
-               /* for each record returned post-process to add any derived
-                  attributes that have been asked for */
-               if (!inject_extended_dn(ares->message, ldb, ac->extended_type, ac->remove_guid, ac->remove_sid)) {
-                       goto error;
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
+
+       switch (ares->type) {
+       case LDB_REPLY_ENTRY:
+               if (ac->inject) {
+                       /* for each record returned post-process to add any derived
+                          attributes that have been asked for */
+                       ret = inject_extended_dn(ares->message, ac->module->ldb,
+                                                ac->extended_type, ac->remove_guid,
+                                                ac->remove_sid);
+                       if (ret != LDB_SUCCESS) {
+                               return ldb_module_done(ac->req, NULL, NULL, ret);
+                       }
                }
+
+               return ldb_module_send_entry(ac->req, ares->message);
+
+       case LDB_REPLY_REFERRAL:
+               return ldb_module_send_referral(ac->req, ares->referral);
+
+       case LDB_REPLY_DONE:
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, LDB_SUCCESS);
+
+       }
+       return LDB_SUCCESS;
+}
+
+static int extended_base_callback(struct ldb_request *req, struct ldb_reply *ares)
+{
+       struct extended_context *ac;
+       struct ldb_request *down_req;
+       struct ldb_control **saved_controls;
+       struct ldb_message_element *el;
+       int ret;
+       size_t i;
+       size_t wkn_len = 0;
+       char *valstr = NULL;
+       const char *found = NULL;
+
+       ac = talloc_get_type(req->context, struct extended_context);
+
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
        }
 
-       return ac->up_callback(ldb, ac->up_context, ares);
+       switch (ares->type) {
+       case LDB_REPLY_ENTRY:
+               if (!ac->wellknown_object) {
+                       ac->basedn = ares->message->dn;
+                       break;
+               }
+
+               wkn_len = strlen(ac->wellknown_object);
 
-error:
-       talloc_free(ares);
-       return LDB_ERR_OPERATIONS_ERROR;
+               el = ldb_msg_find_element(ares->message, "wellKnownObjects");
+               if (!el) {
+                       ac->basedn = NULL;
+                       break;
+               }
+
+               for (i=0; i < el->num_values; i++) {
+                       valstr = talloc_strndup(ac,
+                                               (const char *)el->values[i].data,
+                                               el->values[i].length);
+                       if (!valstr) {
+                               ldb_oom(ac->module->ldb);
+                               return ldb_module_done(ac->req, NULL, NULL,
+                                                      LDB_ERR_OPERATIONS_ERROR);
+                       }
+
+                       if (strncasecmp(valstr, ac->wellknown_object, wkn_len) != 0) {
+                               talloc_free(valstr);
+                               continue;
+                       }
+
+                       found = &valstr[wkn_len];
+                       break;
+               }
+
+               if (!found) {
+                       break;
+               }
+
+               ac->basedn = ldb_dn_new(ac, ac->module->ldb, found);
+               talloc_free(valstr);
+               if (!ac->basedn) {
+                       ldb_oom(ac->module->ldb);
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                              LDB_ERR_OPERATIONS_ERROR);
+               }
+
+               break;
+
+       case LDB_REPLY_REFERRAL:
+               break;
+
+       case LDB_REPLY_DONE:
+
+               if (!ac->basedn) {
+                       const char *str = talloc_asprintf(req, "Base-DN '%s' not found",
+                                                         ldb_dn_get_linearized(ac->req->op.search.base));
+                       ldb_set_errstring(ac->module->ldb, str);
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                              LDB_ERR_NO_SUCH_OBJECT);
+               }
+
+               ret = ldb_build_search_req_ex(&down_req,
+                                               ac->module->ldb, ac,
+                                               ac->basedn,
+                                               ac->req->op.search.scope,
+                                               ac->req->op.search.tree,
+                                               ac->cast_attrs,
+                                               ac->req->controls,
+                                               ac, extended_callback,
+                                               ac->req);
+               if (ret != LDB_SUCCESS) {
+                       return ldb_module_done(ac->req, NULL, NULL, LDB_ERR_OPERATIONS_ERROR);
+               }
+
+               if (ac->control) {
+                       /* save it locally and remove it from the list */
+                       /* we do not need to replace them later as we
+                        * are keeping the original req intact */
+                       if (!save_controls(ac->control, down_req, &saved_controls)) {
+                               return ldb_module_done(ac->req, NULL, NULL,
+                                                       LDB_ERR_OPERATIONS_ERROR);
+                       }
+               }
+
+               /* perform the search */
+               return ldb_next_request(ac->module, down_req);
+       }
+       return LDB_SUCCESS;
 }
 
 static int extended_search(struct ldb_module *module, struct ldb_request *req)
@@ -239,126 +376,286 @@ static int extended_search(struct ldb_module *module, struct ldb_request *req)
        struct ldb_request *down_req;
        char **new_attrs;
        int ret;
+       struct ldb_dn *base_dn = NULL;
+       enum ldb_scope base_dn_scope = LDB_SCOPE_BASE;
+       const char *base_dn_filter = NULL;
+       const char * const *base_dn_attrs = NULL;
+       char *wellknown_object = NULL;
+       static const char *dnattr[] = {
+               "distinguishedName",
+               NULL
+       };
+       static const char *wkattr[] = {
+               "wellKnownObjects",
+               NULL
+       };
+
+       if (ldb_dn_is_special(req->op.search.base)) {
+               char *dn;
+
+               dn = ldb_dn_alloc_linearized(req, req->op.search.base);
+               if (!dn) {
+                       ldb_oom(module->ldb);
+                       return LDB_ERR_OPERATIONS_ERROR;
+               }
+
+               if (strncasecmp(dn, "<SID=", 5) == 0) {
+                       char *str;
+                       char *valstr;
+                       char *p;
+
+                       p = strchr(dn, '=');
+                       if (!p) {
+                               return LDB_ERR_INVALID_DN_SYNTAX;
+                       }
+
+                       p[0] = '\0';
+                       p++;
+
+                       str = p;
+
+                       p = strchr(str, '>');
+                       if (!p) {
+                               return LDB_ERR_INVALID_DN_SYNTAX;
+                       }
+                       p[0] = '\0';
+
+                       if (strncasecmp(str, "S-", 2) == 0) {
+                               valstr = str;
+                       } else {
+                               DATA_BLOB binary;
+                               binary = strhex_to_data_blob(str);
+                               if (!binary.data) {
+                                       ldb_oom(module->ldb);
+                                       return LDB_ERR_OPERATIONS_ERROR;
+                               }
+                               valstr = ldb_binary_encode(req, binary);
+                               data_blob_free(&binary);
+                               if (!valstr) {
+                                       ldb_oom(module->ldb);
+                                       return LDB_ERR_OPERATIONS_ERROR;
+                               }
+                       }
+
+                       /* TODO: do a search over all partitions */
+                       base_dn = ldb_get_default_basedn(module->ldb);
+                       base_dn_filter = talloc_asprintf(req, "(objectSid=%s)", valstr);
+                       if (!base_dn_filter) {
+                               ldb_oom(module->ldb);
+                               return LDB_ERR_OPERATIONS_ERROR;
+                       }
+                       base_dn_scope = LDB_SCOPE_SUBTREE;
+                       base_dn_attrs = dnattr;
+               } else if (strncasecmp(dn, "<GUID=", 6) == 0) {
+                       char *str;
+                       char *valstr;
+                       char *p;
+
+                       p = strchr(dn, '=');
+                       if (!p) {
+                               return LDB_ERR_INVALID_DN_SYNTAX;
+                       }
+
+                       p[0] = '\0';
+                       p++;
+
+                       str = p;
+
+                       p = strchr(str, '>');
+                       if (!p) {
+                               return LDB_ERR_INVALID_DN_SYNTAX;
+                       }
+                       p[0] = '\0';
+
+                       if (strchr(str, '-')) {
+                               valstr = str;
+                       } else {
+                               DATA_BLOB binary;
+                               binary = strhex_to_data_blob(str);
+                               if (!binary.data) {
+                                       ldb_oom(module->ldb);
+                                       return LDB_ERR_OPERATIONS_ERROR;
+                               }
+                               valstr = ldb_binary_encode(req, binary);
+                               data_blob_free(&binary);
+                               if (!valstr) {
+                                       ldb_oom(module->ldb);
+                                       return LDB_ERR_OPERATIONS_ERROR;
+                               }
+                       }
+
+                       /* TODO: do a search over all partitions */
+                       base_dn = ldb_get_default_basedn(module->ldb);
+                       base_dn_filter = talloc_asprintf(req, "(objectGUID=%s)", valstr);
+                       if (!base_dn_filter) {
+                               ldb_oom(module->ldb);
+                               return LDB_ERR_OPERATIONS_ERROR;
+                       }
+                       base_dn_scope = LDB_SCOPE_SUBTREE;
+                       base_dn_attrs = dnattr;
+               } else if (strncasecmp(dn, "<WKGUID=", 8) == 0) {
+                       char *tail_str;
+                       char *p;
+
+                       p = strchr(dn, ',');
+                       if (!p) {
+                               return LDB_ERR_INVALID_DN_SYNTAX;
+                       }
+
+                       p[0] = '\0';
+                       p++;
+
+                       wellknown_object = talloc_asprintf(req, "B:32:%s:", &dn[8]);
+                       if (!wellknown_object) {
+                               ldb_oom(module->ldb);
+                               return LDB_ERR_OPERATIONS_ERROR;
+                       }
+
+                       tail_str = p;
+                       p = strchr(tail_str, '>');
+                       if (!p) {
+                               return LDB_ERR_INVALID_DN_SYNTAX;
+                       }
+                       p[0] = '\0';
+
+                       base_dn = ldb_dn_new(req, module->ldb, tail_str);
+                       if (!base_dn) {
+                               ldb_oom(module->ldb);
+                               return LDB_ERR_OPERATIONS_ERROR;
+                       }
+                       base_dn_filter = talloc_strdup(req, "(objectClass=*)");
+                       if (!base_dn_filter) {
+                               ldb_oom(module->ldb);
+                               return LDB_ERR_OPERATIONS_ERROR;
+                       }
+                       base_dn_scope = LDB_SCOPE_BASE;
+                       base_dn_attrs = wkattr;
+               }
+               talloc_free(dn);
+       }
 
        /* check if there's an extended dn control */
        control = ldb_request_get_control(req, LDB_CONTROL_EXTENDED_DN_OID);
-       if (control == NULL) {
+       if (control == NULL && base_dn_filter == NULL) {
                /* not found go on */
                return ldb_next_request(module, req);
        }
 
-       if (control->data) {
+       if (control && control->data) {
                extended_ctrl = talloc_get_type(control->data, struct ldb_extended_dn_control);
                if (!extended_ctrl) {
                        return LDB_ERR_PROTOCOL_ERROR;
                }
        }
 
-       ac = talloc(req, struct extended_context);
+       ac = talloc_zero(req, struct extended_context);
        if (ac == NULL) {
                ldb_oom(module->ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
        ac->module = module;
-       ac->up_context = req->context;
-       ac->up_callback = req->callback;
-       ac->attrs = req->op.search.attrs;
+       ac->req = req;
+       ac->control = control;
+       ac->basedn = NULL;
+       ac->wellknown_object = wellknown_object;
+       ac->inject = false;
        ac->remove_guid = false;
        ac->remove_sid = false;
-       if (extended_ctrl) {
-               ac->extended_type = extended_ctrl->type;
-       } else {
-               ac->extended_type = 0;
-       }
-
-       down_req = talloc_zero(req, struct ldb_request);
-       if (down_req == NULL) {
-               ldb_oom(module->ldb);
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       down_req->operation = req->operation;
-       down_req->op.search.base = req->op.search.base;
-       down_req->op.search.scope = req->op.search.scope;
-       down_req->op.search.tree = req->op.search.tree;
 
-       /* check if attrs only is specified, in that case check wether we need to modify them */
-       if (req->op.search.attrs) {
-               if (! is_attr_in_list(req->op.search.attrs, "objectGUID")) {
-                       ac->remove_guid = true;
+       if (control) {
+               ac->inject = true;
+               if (extended_ctrl) {
+                       ac->extended_type = extended_ctrl->type;
+               } else {
+                       ac->extended_type = 0;
                }
-               if (! is_attr_in_list(req->op.search.attrs, "objectSID")) {
-                       ac->remove_sid = true;
-               }
-               if (ac->remove_guid || ac->remove_sid) {
-                       new_attrs = copy_attrs(down_req, req->op.search.attrs);
-                       if (new_attrs == NULL) {
-                               ldb_oom(module->ldb);
-                               return LDB_ERR_OPERATIONS_ERROR;
+
+               /* check if attrs only is specified, in that case check wether we need to modify them */
+               if (req->op.search.attrs) {
+                       if (! is_attr_in_list(req->op.search.attrs, "objectGUID")) {
+                               ac->remove_guid = true;
                        }
-                       
-                       if (ac->remove_guid) {
-                               if (!add_attrs(down_req, &new_attrs, "objectGUID"))
-                                       return LDB_ERR_OPERATIONS_ERROR;
+                       if (! is_attr_in_list(req->op.search.attrs, "objectSID")) {
+                               ac->remove_sid = true;
                        }
-                       if (ac->remove_sid) {
-                               if (!add_attrs(down_req, &new_attrs, "objectSID"))
+                       if (ac->remove_guid || ac->remove_sid) {
+                               new_attrs = copy_attrs(ac, req->op.search.attrs);
+                               if (new_attrs == NULL) {
+                                       ldb_oom(module->ldb);
                                        return LDB_ERR_OPERATIONS_ERROR;
-                       }
+                               }
 
-                       down_req->op.search.attrs = (const char * const *)new_attrs;
+                               if (ac->remove_guid) {
+                                       if (!add_attrs(ac, &new_attrs, "objectGUID"))
+                                               return LDB_ERR_OPERATIONS_ERROR;
+                               }
+                               if (ac->remove_sid) {
+                                       if (!add_attrs(ac, &new_attrs, "objectSID"))
+                                               return LDB_ERR_OPERATIONS_ERROR;
+                               }
+                               ac->cast_attrs = (const char * const *)new_attrs;
+                       } else {
+                               ac->cast_attrs = req->op.search.attrs;
+                       }
                }
        }
 
-       down_req->controls = req->controls;
+       if (base_dn) {
+               ret = ldb_build_search_req(&down_req,
+                                          module->ldb, ac,
+                                          base_dn,
+                                          base_dn_scope,
+                                          base_dn_filter,
+                                          base_dn_attrs,
+                                          NULL,
+                                          ac, extended_base_callback,
+                                          req);
+               if (ret != LDB_SUCCESS) {
+                       return LDB_ERR_OPERATIONS_ERROR;
+               }
 
-       /* save it locally and remove it from the list */
-       /* we do not need to replace them later as we
-        * are keeping the original req intact */
-       if (!save_controls(control, down_req, &saved_controls)) {
-               return LDB_ERR_OPERATIONS_ERROR;
+               /* perform the search */
+               return ldb_next_request(module, down_req);
        }
 
-       down_req->context = ac;
-       down_req->callback = extended_callback;
-       ldb_set_timeout_from_prev_req(module->ldb, req, down_req);
-
-       /* perform the search */
-       ret = ldb_next_request(module, down_req);
+       ret = ldb_build_search_req_ex(&down_req,
+                                       module->ldb, ac,
+                                       req->op.search.base,
+                                       req->op.search.scope,
+                                       req->op.search.tree,
+                                       ac->cast_attrs,
+                                       req->controls,
+                                       ac, extended_callback,
+                                       req);
+       if (ret != LDB_SUCCESS) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
 
-       /* do not free down_req as the call results may be linked to it,
-        * it will be freed when the upper level request get freed */
-       if (ret == LDB_SUCCESS) {
-               req->handle = down_req->handle;
+       if (ac->control) {
+               /* save it locally and remove it from the list */
+               /* we do not need to replace them later as we
+                * are keeping the original req intact */
+               if (!save_controls(control, down_req, &saved_controls)) {
+                       return LDB_ERR_OPERATIONS_ERROR;
+               }
        }
 
-       return ret;
+       /* perform the search */
+       return ldb_next_request(module, down_req);
 }
 
 static int extended_init(struct ldb_module *module)
 {
-       struct ldb_request *req;
        int ret;
 
-       req = talloc(module, struct ldb_request);
-       if (req == NULL) {
-               ldb_oom(module->ldb);
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       req->operation = LDB_REQ_REGISTER_CONTROL;
-       req->op.reg_control.oid = LDB_CONTROL_EXTENDED_DN_OID;
-       req->controls = NULL;
-
-       ret = ldb_request(module->ldb, req);
+       ret = ldb_mod_register_control(module, LDB_CONTROL_EXTENDED_DN_OID);
        if (ret != LDB_SUCCESS) {
-               ldb_debug(module->ldb, LDB_DEBUG_ERROR, "extended_dn: Unable to register control with rootdse!\n");
-               talloc_free(req);
+               ldb_debug(module->ldb, LDB_DEBUG_ERROR,
+                       "extended_dn: Unable to register control with rootdse!\n");
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       talloc_free(req);
        return ldb_next_init(module);
 }
 
index fd5aa5e18aea56291ee9163c3b23de9fb9bb083d..492ef1c92b6b591733f1eff9410c31aaf06b9f5f 100644 (file)
@@ -1,7 +1,7 @@
 /* 
    ldb database library
 
-   Copyright (C) Simo Sorce  2004-2006
+   Copyright (C) Simo Sorce  2004-2008
    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005
    Copyright (C) Andrew Tridgell 2005
    Copyright (C) Stefan Metzmacher <metze@samba.org> 2007
 #include "dsdb/samdb/samdb.h"
 #include "dsdb/common/flags.h"
 
+struct it_context {
+       struct ldb_module *module;
+       struct ldb_request *req;
+};
+
+static int it_callback(struct ldb_request *req, struct ldb_reply *ares)
+{
+       struct it_context *ac;
+
+       ac = talloc_get_type(req->context, struct it_context);
+
+
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
+
+       if (ares->type != LDB_REPLY_DONE) {
+               ldb_set_errstring(req->handle->ldb, "Invalid reply type!");
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+
+       return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+}
+
 /* add_record: add instancetype attribute */
 static int instancetype_add(struct ldb_module *module, struct ldb_request *req)
 {
        struct ldb_request *down_req;
        struct ldb_message *msg;
+       struct it_context *ac;
        uint32_t instance_type;
        int ret;
        const struct ldb_control *partition_ctrl;
@@ -70,18 +102,16 @@ static int instancetype_add(struct ldb_module *module, struct ldb_request *req)
                                    struct dsdb_control_current_partition);
        SMB_ASSERT(partition && partition->version == DSDB_CONTROL_CURRENT_PARTITION_VERSION);
 
-       down_req = talloc(req, struct ldb_request);
-       if (down_req == NULL) {
-               ldb_oom(module->ldb);
+       ac = talloc(req, struct it_context);
+       if (ac == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
-
-       *down_req = *req;
+       ac->module = module;
+       ac->req = req;
 
        /* we have to copy the message as the caller might have it as a const */
-       down_req->op.add.message = msg = ldb_msg_copy_shallow(down_req, req->op.add.message);
+       msg = ldb_msg_copy_shallow(ac, req->op.add.message);
        if (msg == NULL) {
-               talloc_free(down_req);
                ldb_oom(module->ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
@@ -99,23 +129,21 @@ static int instancetype_add(struct ldb_module *module, struct ldb_request *req)
 
        ret = ldb_msg_add_fmt(msg, "instanceType", "%u", instance_type);
        if (ret != LDB_SUCCESS) {
-               talloc_free(down_req);
                ldb_oom(module->ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       ldb_set_timeout_from_prev_req(module->ldb, req, down_req);
-
-       /* go on with the call chain */
-       ret = ldb_next_request(module, down_req);
-
-       /* do not free down_req as the call results may be linked to it,
-        * it will be freed when the upper level request get freed */
-       if (ret == LDB_SUCCESS) {
-               req->handle = down_req->handle;
+       ret = ldb_build_add_req(&down_req, module->ldb, ac,
+                               msg,
+                               req->controls,
+                               ac, it_callback,
+                               req);
+       if (ret != LDB_SUCCESS) {
+               return ret;
        }
 
-       return ret;
+       /* go on with the call chain */
+       return ldb_next_request(module, down_req);
 }
 
 _PUBLIC_ const struct ldb_module_ops ldb_instancetype_module_ops = {
index 6836f95873ef81b61a0e8f7f41d2b0913157865b..6e6da5581d628488fc2b5d44f607f3abf91b778b 100644 (file)
@@ -2,7 +2,7 @@
    ldb database library
 
    Copyright (C) Andrew Bartlett 2005
-   Copyright (C) Simo Sorce 2006
+   Copyright (C) Simo Sorce 2006-2008
 
     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
@@ -74,15 +74,14 @@ static const char *user_name(TALLOC_CTX *mem_ctx, struct ldb_module *module)
 struct kludge_acl_context {
 
        struct ldb_module *module;
-       void *up_context;
-       int (*up_callback)(struct ldb_context *, void *, struct ldb_reply *);
+       struct ldb_request *req;
 
        enum security_user_level user_type;
        bool allowedAttributes;
        bool allowedAttributesEffective;
        bool allowedChildClasses;
        bool allowedChildClassesEffective;
-       const char **attrs;
+       const char * const *attrs;
 };
 
 /* read all objectClasses */
@@ -191,6 +190,7 @@ static int kludge_acl_childClasses(struct ldb_context *ldb, struct ldb_message *
                      (comparison_fn_t)data_blob_cmp);
        
                for (i=1 ; i < allowedClasses->num_values; i++) {
+
                        struct ldb_val *val1 = &allowedClasses->values[i-1];
                        struct ldb_val *val2 = &allowedClasses->values[i];
                        if (data_blob_cmp(val1, val2) == 0) {
@@ -207,80 +207,111 @@ static int kludge_acl_childClasses(struct ldb_context *ldb, struct ldb_message *
 
 /* find all attributes allowed by all these objectClasses */
 
-static int kludge_acl_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares)
+static int kludge_acl_callback(struct ldb_request *req, struct ldb_reply *ares)
 {
        struct kludge_acl_context *ac;
        struct kludge_private_data *data;
        int i, ret;
 
-       ac = talloc_get_type(context, struct kludge_acl_context);
+       ac = talloc_get_type(req->context, struct kludge_acl_context);
        data = talloc_get_type(ac->module->private_data, struct kludge_private_data);
 
-       if (ares->type != LDB_REPLY_ENTRY) {
-               return ac->up_callback(ldb, ac->up_context, ares);
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
        }
 
-       if (ac->allowedAttributes) {
-               ret = kludge_acl_allowedAttributes(ldb, ares->message, "allowedAttributes");
-               if (ret != LDB_SUCCESS) {
-                       return ret;
-
+       switch (ares->type) {
+       case LDB_REPLY_ENTRY:
+               if (ac->allowedAttributes) {
+                       ret = kludge_acl_allowedAttributes(ac->module->ldb,
+                                                  ares->message,
+                                                  "allowedAttributes");
+                       if (ret != LDB_SUCCESS) {
+                               return ldb_module_done(ac->req, NULL, NULL, ret);
+                       }
                }
-       }
-       if (ac->allowedChildClasses) {
-               ret = kludge_acl_childClasses(ldb, ares->message, "allowedChildClasses");
-               if (ret != LDB_SUCCESS) {
-                       return ret;
+               if (ac->allowedChildClasses) {
+                       ret = kludge_acl_childClasses(ac->module->ldb,
+                                               ares->message,
+                                               "allowedChildClasses");
+                       if (ret != LDB_SUCCESS) {
+                               return ldb_module_done(ac->req, NULL, NULL, ret);
+                       }
                }
-       }
 
-       if (data && data->password_attrs) /* if we are not initialized just get through */
-       {
-               switch (ac->user_type) {
-               case SECURITY_SYSTEM:
-                       if (ac->allowedAttributesEffective) {
-                               ret = kludge_acl_allowedAttributes(ldb, ares->message, "allowedAttributesEffective");
-                               if (ret != LDB_SUCCESS) {
-                                       return ret;
+               if (data && data->password_attrs) /* if we are not initialized just get through */
+               {
+                       switch (ac->user_type) {
+                       case SECURITY_SYSTEM:
+                               if (ac->allowedAttributesEffective) {
+                                       ret = kludge_acl_allowedAttributes(ac->module->ldb, ares->message,
+                                                                       "allowedClassesAttributesEffective");
+                                       if (ret != LDB_SUCCESS) {
+                                               return ldb_module_done(ac->req, NULL, NULL, ret);
+                                       }
                                }
-                       }
-                       if (ac->allowedChildClassesEffective) {
-                               ret = kludge_acl_childClasses(ldb, ares->message, "allowedChildClassesEffective");
-                               if (ret != LDB_SUCCESS) {
-                                       return ret;
+                               if (ac->allowedChildClassesEffective) {
+                                       ret = kludge_acl_childClasses(ac->module->ldb, ares->message,
+                                                                       "allowedClassesChildClassesEffective");
+                                       if (ret != LDB_SUCCESS) {
+                                               return ldb_module_done(ac->req, NULL, NULL, ret);
+                                       }
                                }
-                       }
-                       break;
-               case SECURITY_ADMINISTRATOR:
-                       if (ac->allowedAttributesEffective) {
-                               ret = kludge_acl_allowedAttributes(ldb, ares->message, "allowedAttributesEffective");
-                               if (ret != LDB_SUCCESS) {
-                                       return ret;
+                               break;
+
+                       case SECURITY_ADMINISTRATOR:
+                               if (ac->allowedAttributesEffective) {
+                                       ret = kludge_acl_allowedAttributes(ac->module->ldb, ares->message,
+                                                                       "allowedClassesAttributesEffective");
+                                       if (ret != LDB_SUCCESS) {
+                                               return ldb_module_done(ac->req, NULL, NULL, ret);
+                                       }
                                }
-                       }
-                       if (ac->allowedChildClassesEffective) {
-                               ret = kludge_acl_childClasses(ldb, ares->message, "allowedChildClassesEffective");
-                               if (ret != LDB_SUCCESS) {
-                                       return ret;
+                               if (ac->allowedChildClassesEffective) {
+                                       ret = kludge_acl_childClasses(ac->module->ldb, ares->message,
+                                                                       "allowedClassesChildClassesEffective");
+                                       if (ret != LDB_SUCCESS) {
+                                               return ldb_module_done(ac->req, NULL, NULL, ret);
+                                       }
+                               }
+                               /* fall through */
+                       default:
+                               /* remove password attributes */
+                               for (i = 0; data->password_attrs[i]; i++) {
+                                       ldb_msg_remove_attr(ares->message, data->password_attrs[i]);
                                }
                        }
-                       /* fall though */
-               default:
-                       /* remove password attributes */
-                       for (i = 0; data->password_attrs[i]; i++) {
-                               ldb_msg_remove_attr(ares->message, data->password_attrs[i]);
+               }
+
+               if (ac->allowedAttributes ||
+                   ac->allowedAttributesEffective ||
+                   ac->allowedChildClasses ||
+                   ac->allowedChildClassesEffective) {
+
+                       if (!ldb_attr_in_list(ac->attrs, "objectClass") &&
+                           !ldb_attr_in_list(ac->attrs, "*")) {
+
+                               ldb_msg_remove_attr(ares->message,
+                                                   "objectClass");
                        }
                }
-       }
 
-       if ((ac->allowedAttributes || ac->allowedAttributesEffective
-            || ac->allowedChildClasses || ac->allowedChildClassesEffective) && 
-           (!ldb_attr_in_list(ac->attrs, "objectClass") && 
-            !ldb_attr_in_list(ac->attrs, "*"))) {
-               ldb_msg_remove_attr(ares->message, "objectClass");
-       }
+               return ldb_module_send_entry(ac->req, ares->message);
+
+       case LDB_REPLY_REFERRAL:
+               return ldb_module_send_referral(ac->req, ares->referral);
 
-       return ac->up_callback(ldb, ac->up_context, ares);
+       case LDB_REPLY_DONE:
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, LDB_SUCCESS);
+
+       }
+       return LDB_SUCCESS;
 }
 
 static int kludge_acl_search(struct ldb_module *module, struct ldb_request *req)
@@ -288,9 +319,10 @@ static int kludge_acl_search(struct ldb_module *module, struct ldb_request *req)
        struct kludge_acl_context *ac;
        struct ldb_request *down_req;
        struct kludge_private_data *data;
+       const char * const *attrs;
        int ret, i;
-
-       req->handle = NULL;
+       struct ldb_control *sd_control;
+       struct ldb_control **sd_saved_controls;
 
        ac = talloc(req, struct kludge_acl_context);
        if (ac == NULL) {
@@ -301,23 +333,10 @@ static int kludge_acl_search(struct ldb_module *module, struct ldb_request *req)
        data = talloc_get_type(module->private_data, struct kludge_private_data);
 
        ac->module = module;
-       ac->up_context = req->context;
-       ac->up_callback = req->callback;
+       ac->req = req;
        ac->user_type = what_is_user(module);
        ac->attrs = req->op.search.attrs;
 
-       down_req = talloc_zero(req, struct ldb_request);
-       if (down_req == NULL) {
-               ldb_oom(module->ldb);
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       down_req->operation = req->operation;
-       down_req->op.search.base = req->op.search.base;
-       down_req->op.search.scope = req->op.search.scope;
-       down_req->op.search.tree = req->op.search.tree;
-       down_req->op.search.attrs = req->op.search.attrs;
-
        ac->allowedAttributes = ldb_attr_in_list(req->op.search.attrs, "allowedAttributes");
 
        ac->allowedAttributesEffective = ldb_attr_in_list(req->op.search.attrs, "allowedAttributesEffective");
@@ -327,12 +346,11 @@ static int kludge_acl_search(struct ldb_module *module, struct ldb_request *req)
        ac->allowedChildClassesEffective = ldb_attr_in_list(req->op.search.attrs, "allowedChildClassesEffective");
 
        if (ac->allowedAttributes || ac->allowedAttributesEffective || ac->allowedChildClasses || ac->allowedChildClassesEffective) {
-               down_req->op.search.attrs
-                       = ldb_attr_list_copy_add(down_req, down_req->op.search.attrs, "objectClass");
+               attrs = ldb_attr_list_copy_add(ac, req->op.search.attrs, "objectClass");
+       } else {
+               attrs = req->op.search.attrs;
        }
 
-       /*  FIXME: I hink we should copy the tree and keep the original
-        *  unmodified. SSS */
        /* replace any attributes in the parse tree that are private,
           so we don't allow a search for 'userPassword=penguin',
           just as we would not allow that attribute to be returned */
@@ -340,30 +358,45 @@ static int kludge_acl_search(struct ldb_module *module, struct ldb_request *req)
        case SECURITY_SYSTEM:
                break;
        default:
+       /* FIXME: We should copy the tree and keep the original unmodified. */
                /* remove password attributes */
-               for (i = 0; data && data->password_attrs && data->password_attrs[i]; i++) {
-                       ldb_parse_tree_attr_replace(down_req->op.search.tree, 
+
+               if (!data || !data->password_attrs) {
+                       break;
+               }
+               for (i = 0; data->password_attrs[i]; i++) {
+                       ldb_parse_tree_attr_replace(req->op.search.tree,
                                                    data->password_attrs[i],
                                                    "kludgeACLredactedattribute");
                }
        }
 
-       down_req->controls = req->controls;
-
-       down_req->context = ac;
-       down_req->callback = kludge_acl_callback;
-       ldb_set_timeout_from_prev_req(module->ldb, req, down_req);
-
-       /* perform the search */
-       ret = ldb_next_request(module, down_req);
+       ret = ldb_build_search_req_ex(&down_req,
+                                       module->ldb, ac,
+                                       req->op.search.base,
+                                       req->op.search.scope,
+                                       req->op.search.tree,
+                                       attrs,
+                                       req->controls,
+                                       ac, kludge_acl_callback,
+                                       req);
+       if (ret != LDB_SUCCESS) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
 
-       /* do not free down_req as the call results may be linked to it,
-        * it will be freed when the upper level request get freed */
-       if (ret == LDB_SUCCESS) {
-               req->handle = down_req->handle;
+       /* check if there's an SD_FLAGS control */
+       sd_control = ldb_request_get_control(down_req, LDB_CONTROL_SD_FLAGS_OID);
+       if (sd_control) {
+               /* save it locally and remove it from the list */
+               /* we do not need to replace them later as we
+                * are keeping the original req intact */
+               if (!save_controls(sd_control, down_req, &sd_saved_controls)) {
+                       return LDB_ERR_OPERATIONS_ERROR;
+               }
        }
 
-       return ret;
+       /* perform the search */
+       return ldb_next_request(module, down_req);
 }
 
 /* ANY change type */
@@ -442,6 +475,13 @@ static int kludge_acl_init(struct ldb_module *module)
        }
        data->password_attrs[i] = NULL;
 
+       ret = ldb_mod_register_control(module, LDB_CONTROL_SD_FLAGS_OID);
+       if (ret != LDB_SUCCESS) {
+               ldb_debug(module->ldb, LDB_DEBUG_ERROR,
+                       "partition: Unable to register control with rootdse!\n");
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
 done:
        talloc_free(mem_ctx);
        return ldb_next_init(module);
index e64472432d21d2293b1bfd173144a1942a16169e..14fd107d81d504f347f39bfde334121fb317ffee 100644 (file)
@@ -2,6 +2,7 @@
    ldb database library
 
    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2007
+   Copyright (C) Simo Sorce <idra@samba.org> 2008
 
    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
 #include "ldb/include/ldb_private.h"
 #include "dsdb/samdb/samdb.h"
 
-struct linked_attributes_context {
-       enum la_step {LA_SEARCH, LA_DO_OPS, LA_DO_ORIG} step;
-       struct ldb_module *module;
-       struct ldb_handle *handle;
-       struct ldb_request *orig_req;
-
-       struct ldb_request *search_req;
-       struct ldb_request **down_req;
-       struct ldb_request *orig_down_req;
-
-       int num_requests;
-       int finished_requests;
-
-       const char **linked_attrs;
+struct la_op_store {
+       struct la_op_store *next;
+       enum la_op {LA_OP_ADD, LA_OP_DEL} op;
+       struct ldb_dn *dn;
+       char *name;
+       char *value;
 };
 
 struct replace_context {
-       struct linked_attributes_context *ac;
+       struct la_context *ac;
+       unsigned int num_elements;
        struct ldb_message_element *el;
 };
 
-static int linked_attributes_rename_del_search_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares);
-
-static struct linked_attributes_context *linked_attributes_init_handle(struct ldb_request *req, 
-                                                                struct ldb_module *module)
-{
-       struct linked_attributes_context *ac;
-       struct ldb_handle *h;
+struct la_context {
+       const struct dsdb_schema *schema;
+       struct ldb_module *module;
+       struct ldb_request *req;
 
-       h = talloc_zero(req, struct ldb_handle);
-       if (h == NULL) {
-               ldb_set_errstring(module->ldb, "Out of Memory");
-               return NULL;
-       }
+       struct replace_context *rc;
+       struct la_op_store *ops;
+       struct la_op_store *cur;
+};
 
-       h->module = module;
+static struct la_context *linked_attributes_init(struct ldb_module *module,
+                                                struct ldb_request *req)
+{
+       struct la_context *ac;
 
-       ac = talloc_zero(h, struct linked_attributes_context);
+       ac = talloc_zero(req, struct la_context);
        if (ac == NULL) {
                ldb_set_errstring(module->ldb, "Out of Memory");
-               talloc_free(h);
                return NULL;
        }
 
-       h->private_data = ac;
-
+       ac->schema = dsdb_get_schema(module->ldb);
        ac->module = module;
-       ac->handle = h;
-       ac->orig_req = req;
-       
-       ac->orig_down_req = talloc(ac, struct ldb_request);
-       if (!ac->orig_down_req) {
-               ldb_oom(ac->module->ldb);
-               return NULL;
-       }
-
-       *ac->orig_down_req = *req;
-
-       req->handle = h;
+       ac->req = req;
 
        return ac;
 }
 
 /* Common routine to handle reading the attributes and creating a
  * series of modify requests */
-
-static int setup_modifies(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, 
-                         struct linked_attributes_context *ac,
-                         const struct ldb_message *msg, 
-                         struct ldb_dn *olddn, struct ldb_dn *newdn) 
+static int la_store_op(struct la_context *ac,
+                       enum la_op op, char *dn,
+                       const char *name, const char *value)
 {
-       int i, j, ret = LDB_SUCCESS;
-       const struct dsdb_schema *schema = dsdb_get_schema(ldb);
-       /* Look up each of the returned attributes */
-       /* Find their schema */
-       /* And it is an actual entry: now create a series of modify requests */
-       for (i=0; i < msg->num_elements; i++) {
-               int otherid;
-               const struct dsdb_attribute *target_attr;
-               const struct ldb_message_element *el = &msg->elements[i];
-               const struct dsdb_attribute *schema_attr
-                       = dsdb_attribute_by_lDAPDisplayName(schema, el->name);
-               if (!schema_attr) {
-                       ldb_asprintf_errstring(ldb, 
-                                              "attribute %s is not a valid attribute in schema", el->name);
-                       return LDB_ERR_OBJECT_CLASS_VIOLATION;                  
-               }
-               /* We have a valid attribute, but if it's not linked they maybe we just got an extra return on our search... */
-               if (schema_attr->linkID == 0) {
-                       continue;
-               }
-               
-               /* Depending on which direction this link is in, we need to find it's partner */
-               if ((schema_attr->linkID & 1) == 1) {
-                       otherid = schema_attr->linkID - 1;
-               } else {
-                       otherid = schema_attr->linkID + 1;
-               }
-               
-               /* Now find the target attribute */
-               target_attr = dsdb_attribute_by_linkID(schema, otherid);
-               if (!target_attr) {
-                       ldb_asprintf_errstring(ldb, 
-                                              "attribute %s does not have valid link target", el->name);
-                       return LDB_ERR_OBJECT_CLASS_VIOLATION;                  
-               }
-               
-               /* For each value being moded, we need to setup the modify */
-               for (j=0; j < el->num_values; j++) {
-                       struct ldb_message_element *ret_el;
-                       struct ldb_request *new_req;
-                       struct ldb_message *new_msg;
-
-                       /* Create a spot in the list for the requests */
-                       ac->down_req = talloc_realloc(ac, ac->down_req, 
-                                                     struct ldb_request *, ac->num_requests + 1);
-                       if (!ac->down_req) {
-                               ldb_oom(ldb);
-                               return LDB_ERR_OPERATIONS_ERROR;
-                       }
+       struct la_op_store *os, *tmp;
+       struct ldb_dn *op_dn;
 
-                       /* Create the modify request */
-                       new_msg = ldb_msg_new(ac->down_req);
-                       if (!new_msg) {
-                               ldb_oom(ldb);
-                               return LDB_ERR_OPERATIONS_ERROR;
-                       }
-                       new_msg->dn = ldb_dn_from_ldb_val(new_msg, ldb, &el->values[j]);
-                       if (!new_msg->dn) {
-                               ldb_asprintf_errstring(ldb, 
-                                                      "attribute %s value %s was not a valid DN", msg->elements[i].name,
-                                                      el->values[j].data);
-                               return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
-                       }
-                       
-                       if (olddn) {
-                               ret = ldb_msg_add_empty(new_msg, target_attr->lDAPDisplayName, 
-                                                       LDB_FLAG_MOD_DELETE, &ret_el);
-                               if (ret != LDB_SUCCESS) {
-                                       return ret;
-                               }       
-                               ret_el->values = talloc_array(new_msg, struct ldb_val, 1);
-                               if (!ret_el->values) {
-                                       ldb_oom(ldb);
-                                       return LDB_ERR_OPERATIONS_ERROR;
-                               }
-                               ret_el->values[0] = data_blob_string_const(ldb_dn_get_linearized(olddn));
-                               ret_el->num_values = 1;
-                       }
-                       
-                       if (newdn) {
-                               ret = ldb_msg_add_empty(new_msg, target_attr->lDAPDisplayName, 
-                                                       LDB_FLAG_MOD_ADD, &ret_el);
-                               if (ret != LDB_SUCCESS) {
-                                       return ret;
-                               }       
-                               ret_el->values = talloc_array(new_msg, struct ldb_val, 1);
-                               if (!ret_el->values) {
-                                       ldb_oom(ldb);
-                                       return LDB_ERR_OPERATIONS_ERROR;
+       op_dn = ldb_dn_new(ac, ac->module->ldb, dn);
+       if (!op_dn) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       /* optimize out del - add operations that would end up
+        * with no changes */
+       if (ac->ops && op == LA_OP_DEL) {
+               /* do a linear search to find out if there is
+                * an equivalent add */
+               os = ac->ops;
+               while (os->next) {
+
+                       tmp = os->next;
+                       if (tmp->op == LA_OP_ADD) {
+
+                               if ((strcmp(name, tmp->name) == 0) &&
+                                   (strcmp(value, tmp->value) == 0) &&
+                                   (ldb_dn_compare(op_dn, tmp->dn) == 0)) {
+
+                                       break;
                                }
-                               ret_el->values[0] = data_blob_string_const(ldb_dn_get_linearized(newdn));
-                               ret_el->num_values = 1;
                        }
+                       os = os->next;
+               }
+               if (os->next) {
+                       /* pair found, remove it and return */
+                       os->next = tmp->next;
+                       talloc_free(tmp);
+                       talloc_free(op_dn);
+                       return LDB_SUCCESS;
+               }
+       }
 
-                       ret = ldb_build_mod_req(&new_req, ldb, ac->down_req,
-                                               new_msg,
-                                               NULL,
-                                               NULL,
-                                               NULL);
-                       if (ret != LDB_SUCCESS) {
-                               return ret;
-                       }
-                       
-                       talloc_steal(new_req, new_msg);
-                       
-                       ldb_set_timeout_from_prev_req(ldb, ac->orig_req, new_req);
-                       
-                       ac->down_req[ac->num_requests] = new_req;
-                       ac->num_requests++;
-                       
-
-                       /* Run the new request */
-                       ret = ldb_next_request(ac->module, new_req);
-                       if (ret != LDB_SUCCESS) {
-                               return ret;
-                       }
+       os = talloc_zero(ac, struct la_op_store);
+       if (!os) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       os->op = op;
+
+       os->dn = talloc_steal(os, op_dn);
+       if (!os->dn) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       os->name = talloc_strdup(os, name);
+       if (!os->name) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       if ((op != LA_OP_DEL) && (value == NULL)) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+       if (value) {
+               os->value = talloc_strdup(os, value);
+               if (!os->value) {
+                       return LDB_ERR_OPERATIONS_ERROR;
                }
        }
-       return ret;
+
+       if (ac->ops) {
+               ac->cur->next = os;
+       } else {
+               ac->ops = os;
+       }
+       ac->cur = os;
+
+       return LDB_SUCCESS;
 }
 
+static int la_op_search_callback(struct ldb_request *req,
+                                struct ldb_reply *ares);
+static int la_do_mod_request(struct la_context *ac);
+static int la_mod_callback(struct ldb_request *req,
+                          struct ldb_reply *ares);
+static int la_down_req(struct la_context *ac);
+static int la_down_callback(struct ldb_request *req,
+                           struct ldb_reply *ares);
+
+
+
 /* add */
 static int linked_attributes_add(struct ldb_module *module, struct ldb_request *req)
 {
-       int i;
-       struct linked_attributes_context *ac;
-
-       const struct dsdb_schema *schema = dsdb_get_schema(module->ldb);
-       if (!schema) {
-               /* without schema, this doesn't make any sense */
-               return ldb_next_request(module, req);
-       }
+       const struct dsdb_attribute *target_attr;
+       struct la_context *ac;
+       const char *attr_name;
+       const char *attr_val;
+       int ret;
+       int i, j;
 
        if (ldb_dn_is_special(req->op.mod.message->dn)) {
                /* do not manipulate our control entries */
                return ldb_next_request(module, req);
        }
 
-
-       ac = linked_attributes_init_handle(req, module);
+       ac = linked_attributes_init(module, req);
        if (!ac) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       
-       ac->step = LA_DO_OPS;
-       
+
+       if (!ac->schema) {
+               /* without schema, this doesn't make any sense */
+               talloc_free(ac);
+               return ldb_next_request(module, req);
+       }
+
        /* Need to ensure we only have forward links being specified */
        for (i=0; i < req->op.add.message->num_elements; i++) {
                const struct ldb_message_element *el = &req->op.add.message->elements[i];
                const struct dsdb_attribute *schema_attr
-                       = dsdb_attribute_by_lDAPDisplayName(schema, el->name);
+                       = dsdb_attribute_by_lDAPDisplayName(ac->schema, el->name);
                if (!schema_attr) {
                        ldb_asprintf_errstring(module->ldb, 
-                                              "attribute %s is not a valid attribute in schema", req->op.add.message->elements[i].name);
+                                              "attribute %s is not a valid attribute in schema", el->name);
                        return LDB_ERR_OBJECT_CLASS_VIOLATION;                  
                }
-               /* We have a valid attribute, not find out if it is linked */
+               /* We have a valid attribute, now find out if it is linked */
                if (schema_attr->linkID == 0) {
                        continue;
                }
@@ -268,160 +211,155 @@ static int linked_attributes_add(struct ldb_module *module, struct ldb_request *
                if ((schema_attr->linkID & 1) == 1) {
                        /* Odd is for the target.  Illigal to modify */
                        ldb_asprintf_errstring(module->ldb, 
-                                              "attribute %s must not be modified directly, it is a linked attribute", req->op.add.message->elements[i].name);
+                                              "attribute %s must not be modified directly, it is a linked attribute", el->name);
                        return LDB_ERR_UNWILLING_TO_PERFORM;
                }
                
                /* Even link IDs are for the originating attribute */
-       }
-
-       /* Now call the common routine to setup the modifies across all the attributes */
-       return setup_modifies(module->ldb, ac, ac, req->op.add.message, NULL, req->op.add.message->dn);
-}
+               target_attr = dsdb_attribute_by_linkID(ac->schema, schema_attr->linkID + 1);
+               if (!target_attr) {
+                       /*
+                        * windows 2003 has a broken schema where
+                        * the definition of msDS-IsDomainFor
+                        * is missing (which is supposed to be
+                        * the backlink of the msDS-HasDomainNCs
+                        * attribute
+                        */
+                       continue;
+               }
 
-struct merge {
-       struct ldb_dn *dn;
-       bool add;
-       bool ignore;
-};
+               attr_name = target_attr->lDAPDisplayName;
+               attr_val = ldb_dn_get_linearized(ac->req->op.add.message->dn);
 
-static int merge_cmp(struct merge *merge1, struct merge *merge2) {
-       int ret;
-       ret = ldb_dn_compare(merge1->dn, merge2->dn);
-       if (ret == 0) {
-               if (merge1->add == merge2->add) {
-                       return 0;
-               }
-               if (merge1->add == true) {
-                       return 1;
+               for (j = 0; j < el->num_values; j++) {
+                       ret = la_store_op(ac, LA_OP_ADD,
+                                         (char *)el->values[j].data,
+                                         attr_name, attr_val);
+                       if (ret != LDB_SUCCESS) {
+                               return ret;
+                       }
                }
-               return -1;
        }
-       return ret;
+
+       /* if no linked attributes are present continue */
+       if (ac->ops == NULL) {
+               talloc_free(ac);
+               return ldb_next_request(module, req);
+       }
+
+       /* start with the first one */
+       return la_do_mod_request(ac);
 }
 
-static int linked_attributes_mod_replace_search_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares) 
+static int la_mod_search_callback(struct ldb_request *req, struct ldb_reply *ares)
 {
-       struct replace_context *ac2 = talloc_get_type(context, struct replace_context);
-       struct linked_attributes_context *ac = ac2->ac;
-    
-       /* OK, we have one search result here: */
+       const struct dsdb_attribute *schema_attr;
+       const struct dsdb_attribute *target_attr;
+       struct ldb_message_element *search_el;
+       struct replace_context *rc;
+       struct la_context *ac;
+       const char *attr_name;
+       const char *dn;
+       int i, j;
+       int ret = LDB_SUCCESS;
 
-       /* Only entries are interesting, and we only want the olddn */
-       if (ares->type == LDB_REPLY_ENTRY
-           && ldb_dn_compare(ares->message->dn, ac->orig_req->op.mod.message->dn) == 0) {
-               /* only bother at all if there were some linked attributes found */
-               struct ldb_message_element *search_el
-                       = ldb_msg_find_element(ares->message,
-                                              ac2->el->name);
-               
-               /* See if this element already exists */
-               if (search_el) {
+       ac = talloc_get_type(req->context, struct la_context);
+       rc = ac->rc;
+
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
 
-                       struct merge *merged_list = NULL;
+       /* Only entries are interesting, and we only want the olddn */
+       switch (ares->type) {
+       case LDB_REPLY_ENTRY:
+
+               if (ldb_dn_compare(ares->message->dn, ac->req->op.mod.message->dn) != 0) {
+                       /* Guh?  We only asked for this DN */
+                       ldb_oom(ac->module->ldb);
+                       talloc_free(ares);
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
+               }
 
-                       int ret, size = 0, i;
-                       struct ldb_message *msg = ldb_msg_new(ac);
-                       if (!msg) {
-                               ldb_oom(ac->module->ldb);
-                               return LDB_ERR_OPERATIONS_ERROR;
-                       }
+               dn = ldb_dn_get_linearized(ac->req->op.add.message->dn);
 
-                       /* Add all the existing elements, marking as 'proposed for delete' by setting .add = false */
-                       for (i=0; i < search_el->num_values; i++) {
-                               merged_list = talloc_realloc(ares, merged_list, struct merge, size + 1);
-                               merged_list[size].dn = ldb_dn_from_ldb_val(merged_list, ldb, &search_el->values[i]);
-                               merged_list[size].add = false;
-                               merged_list[size].ignore = false;
-                               size++;
-                       }
+               for (i = 0; i < rc->num_elements; i++) {
 
-                       /* Add all the new replacement elements, marking as 'proposed for add' by setting .add = true */
-                       for (i=0; i < ac2->el->num_values; i++) {
-                               merged_list = talloc_realloc(ares, merged_list, struct merge, size + 1);
-                               merged_list[size].dn = ldb_dn_from_ldb_val(merged_list, ldb, &ac2->el->values[i]);
-                               merged_list[size].add = true;
-                               merged_list[size].ignore = false;
-                               size++;
+                       schema_attr = dsdb_attribute_by_lDAPDisplayName(ac->schema, rc->el[i].name);
+                       if (!schema_attr) {
+                               ldb_asprintf_errstring(ac->module->ldb,
+                                       "attribute %s is not a valid attribute in schema",
+                                       rc->el[i].name);
+                               talloc_free(ares);
+                               return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OBJECT_CLASS_VIOLATION);
                        }
 
-                       /* Sort the list, so we can pick out an add and delete for the same DN, and eliminate them */
-                       qsort(merged_list, size,
-                             sizeof(*merged_list),
-                             (comparison_fn_t)merge_cmp);
-
-                       /* Now things are sorted, it is trivial to mark pairs of DNs as 'ignore' */
-                       for (i=0; i + 1 < size; i++) {
-                               if (ldb_dn_compare(merged_list[i].dn, 
-                                                  merged_list[i+1].dn) == 0 
-                                   /* Fortunetly the sort also sorts 'add == false' first */
-                                   && merged_list[i].add == false
-                                   && merged_list[i+1].add == true) {
-
-                                       /* Mark as ignore, so we include neither in the actual operations */
-                                       merged_list[i].ignore = true;
-                                       merged_list[i+1].ignore = true;
-                               }
-                       }
+                       search_el = ldb_msg_find_element(ares->message,
+                                                        rc->el[i].name);
 
-                       /* Arrange to delete anything the search found that we don't re-add */
-                       for (i=0; i < size; i++) {
-                               if (merged_list[i].ignore == false
-                                   && merged_list[i].add == false) {
-                                       ldb_msg_add_steal_string(msg, search_el->name, 
-                                                                ldb_dn_get_linearized(merged_list[i].dn));
-                               }
+                       /* See if this element already exists */
+                       /* otherwise just ignore as
+                        * the add has already been scheduled */
+                       if ( ! search_el) {
+                               continue;
                        }
 
-                       /* The DN to set on the linked attributes is the original DN of the modify message */
-                       msg->dn = ac->orig_req->op.mod.message->dn;
-                       
-                       ret = setup_modifies(ac->module->ldb, ac2, ac, msg, ares->message->dn, NULL);
-                       if (ret != LDB_SUCCESS) {
-                               return ret;
+                       target_attr = dsdb_attribute_by_linkID(ac->schema, schema_attr->linkID + 1);
+                       if (!target_attr) {
+                               /*
+                                * windows 2003 has a broken schema where
+                                * the definition of msDS-IsDomainFor
+                                * is missing (which is supposed to be
+                                * the backlink of the msDS-HasDomainNCs
+                                * attribute
+                                */
+                               continue;
                        }
+                       attr_name = target_attr->lDAPDisplayName;
 
-                       /* Now add links for all the actually new elements */
-                       for (i=0; i < size; i++) {
-                               if (merged_list[i].ignore == false && merged_list[i].add == true) {
-                                       ldb_msg_add_steal_string(msg, search_el->name, 
-                                                                ldb_dn_get_linearized(merged_list[i].dn));
+                       /* make sure we manage each value */
+                       for (j = 0; j < search_el->num_values; j++) {
+                               ret = la_store_op(ac, LA_OP_DEL,
+                                         (char *)search_el->values[j].data,
+                                                 attr_name, dn);
+                               if (ret != LDB_SUCCESS) {
+                                       talloc_free(ares);
+                                       return ldb_module_done(ac->req,
+                                                              NULL, NULL, ret);
                                }
                        }
+               }
 
-                       ret = setup_modifies(ac->module->ldb, ac2, ac, msg, NULL, ares->message->dn);
-                       if (ret != LDB_SUCCESS) {
-                               return ret;
-                       }
-                       
-                       talloc_free(merged_list);
+               break;
 
-               } else {
-                       /* Looks like it doesn't exist, process like an 'add' */
-                       struct ldb_message *msg = ldb_msg_new(ac);
-                       if (!msg) {
-                               ldb_oom(ac->module->ldb);
-                               return LDB_ERR_OPERATIONS_ERROR;
-                       }
-                       msg->num_elements = 1;
-                       msg->elements = ac2->el;
-                       msg->dn = ac->orig_req->op.mod.message->dn;
+       case LDB_REPLY_REFERRAL:
+               /* ignore */
+               break;
 
-                       return setup_modifies(ac->module->ldb, ac2, ac, msg, NULL, ac->orig_req->op.mod.message->dn);
-               }
-               talloc_free(ares);
-               return LDB_SUCCESS;
-       } else if (ares->type == LDB_REPLY_ENTRY) {
-               /* Guh?  We only asked for this DN */
-               return LDB_ERR_OPERATIONS_ERROR;
+       case LDB_REPLY_DONE:
 
-       } else {
                talloc_free(ares);
+
+               /* All mods set up, start with the first one */
+               ret = la_do_mod_request(ac);
+               if (ret != LDB_SUCCESS) {
+                       return ldb_module_done(ac->req, NULL, NULL, ret);
+               }
                return LDB_SUCCESS;
        }
-       
-       
+
+       talloc_free(ares);
+       return ret;
 }
+
+
 /* modify */
 static int linked_attributes_modify(struct ldb_module *module, struct ldb_request *req)
 {
@@ -431,523 +369,556 @@ static int linked_attributes_modify(struct ldb_module *module, struct ldb_reques
        /* Apply the modify to the linked entry */
 
        int i, j;
-       struct linked_attributes_context *ac;
-
-       const struct dsdb_schema *schema = dsdb_get_schema(module->ldb);
-       if (!schema) {
-               /* without schema, this doesn't make any sense */
-               return ldb_next_request(module, req);
-       }
+       struct la_context *ac;
+       struct ldb_request *search_req;
+       int ret;
 
        if (ldb_dn_is_special(req->op.mod.message->dn)) {
                /* do not manipulate our control entries */
                return ldb_next_request(module, req);
        }
 
-
-       ac = linked_attributes_init_handle(req, module);
+       ac = linked_attributes_init(module, req);
        if (!ac) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       
-       /* prepare the first operation */
-       ac->step = LA_DO_OPS;
+
+       if (!ac->schema) {
+               /* without schema, this doesn't make any sense */
+               return ldb_next_request(module, req);
+       }
+
+       ac->rc = NULL;
 
        for (i=0; i < req->op.mod.message->num_elements; i++) {
-               int ret;
-               struct ldb_request *new_req;
+               bool store_el = false;
+               const char *attr_name;
+               const char *attr_val;
                const struct dsdb_attribute *target_attr;
                const struct ldb_message_element *el = &req->op.mod.message->elements[i];
                const struct dsdb_attribute *schema_attr
-                       = dsdb_attribute_by_lDAPDisplayName(schema, el->name);
+                       = dsdb_attribute_by_lDAPDisplayName(ac->schema, el->name);
                if (!schema_attr) {
                        ldb_asprintf_errstring(module->ldb, 
-                                              "attribute %s is not a valid attribute in schema", req->op.mod.message->elements[i].name);
+                                              "attribute %s is not a valid attribute in schema", el->name);
                        return LDB_ERR_OBJECT_CLASS_VIOLATION;                  
                }
-               /* We have a valid attribute, not find out if it is linked */
+               /* We have a valid attribute, now find out if it is linked */
                if (schema_attr->linkID == 0) {
                        continue;
                }
                
                if ((schema_attr->linkID & 1) == 1) {
-                       /* Odd is for the target.  Illigal to modify */
+                       /* Odd is for the target.  Illegal to modify */
                        ldb_asprintf_errstring(module->ldb, 
-                                              "attribute %s must not be modified directly, it is a linked attribute", req->op.mod.message->elements[i].name);
+                                              "attribute %s must not be modified directly, it is a linked attribute", el->name);
                        return LDB_ERR_UNWILLING_TO_PERFORM;
                }
                
                /* Even link IDs are for the originating attribute */
                
                /* Now find the target attribute */
-               target_attr = dsdb_attribute_by_linkID(schema, schema_attr->linkID + 1);
+               target_attr = dsdb_attribute_by_linkID(ac->schema, schema_attr->linkID + 1);
                if (!target_attr) {
-                       ldb_asprintf_errstring(module->ldb, 
-                                              "attribute %s does not have valid link target", req->op.mod.message->elements[i].name);
-                       return LDB_ERR_OBJECT_CLASS_VIOLATION;                  
+                       /*
+                        * windows 2003 has a broken schema where
+                        * the definition of msDS-IsDomainFor
+                        * is missing (which is supposed to be
+                        * the backlink of the msDS-HasDomainNCs
+                        * attribute
+                        */
+                       continue;
                }
 
-               /* Replace with new set of values */
-               if (((el->flags & LDB_FLAG_MOD_MASK) == LDB_FLAG_MOD_REPLACE)
-                   && el->num_values > 0) {
-                       struct replace_context *ac2 = talloc(ac, struct replace_context);
-                       const char **attrs = talloc_array(ac, const char *, 2);
-                       if (!attrs || !ac2) {
-                               ldb_oom(ac->module->ldb);
-                               return LDB_ERR_OPERATIONS_ERROR;
-                       }
-                       attrs[0] = el->name;
-                       attrs[1] = NULL;
-
-                       ac2->ac = ac;
-                       ac2->el = el;
-
-                       /* We need to setup a search, compare with the list, and then setup add/del as required */
-                       
-                       /* The callback does all the hard work here */
-                       ret = ldb_build_search_req(&new_req, module->ldb, req,
-                                                  req->op.mod.message->dn, 
-                                                  LDB_SCOPE_BASE,
-                                                  "(objectClass=*)",
-                                                  attrs,
-                                                  NULL, 
-                                                  ac2, 
-                                                  linked_attributes_mod_replace_search_callback);
-                       
-                       if (ret != LDB_SUCCESS) {
-                               return ret;
-                       }
-                       
-                       talloc_steal(new_req, attrs);
-                       
-                       ret = ldb_set_timeout_from_prev_req(module->ldb, req, new_req);
-                       
-                       if (ret != LDB_SUCCESS) {
-                               return ret;
-                       }
+               attr_name = target_attr->lDAPDisplayName;
+               attr_val = ldb_dn_get_linearized(ac->req->op.mod.message->dn);
 
-                       /* Create a spot in the list for the requests */
-                       ac->down_req = talloc_realloc(ac, ac->down_req, 
-                                                     struct ldb_request *, ac->num_requests + 1);
-                       if (!ac->down_req) {
-                               ldb_oom(ac->module->ldb);
-                               return LDB_ERR_OPERATIONS_ERROR;
-                       }
+               switch (el->flags & LDB_FLAG_MOD_MASK) {
+               case LDB_FLAG_MOD_REPLACE:
+                       /* treat as just a normal add the delete part is handled by the callback */
+                       store_el = true;
 
-                       ac->down_req[ac->num_requests] = talloc_steal(ac->down_req, new_req);
-                       ac->num_requests++;
+                       /* break intentionally missing */
 
-                       ret = ldb_next_request(module, new_req);
-                       
-                       if (ret != LDB_SUCCESS) {
-                               return ret;
-                       }
-                       
-                       continue;
+               case LDB_FLAG_MOD_ADD:
 
-                       /* Delete all values case */
-               } else if (((el->flags & LDB_FLAG_MOD_MASK) & (LDB_FLAG_MOD_DELETE|LDB_FLAG_MOD_REPLACE)) 
-                          && el->num_values == 0) {
-                       const char **attrs = talloc_array(ac, const char *, 2);
-                       if (!attrs) {
-                               ldb_oom(ac->module->ldb);
-                               return LDB_ERR_OPERATIONS_ERROR;
+                       /* For each value being added, we need to setup the adds */
+                       for (j = 0; j < el->num_values; j++) {
+                               ret = la_store_op(ac, LA_OP_ADD,
+                                         (char *)el->values[j].data,
+                                                 attr_name, attr_val);
+                               if (ret != LDB_SUCCESS) {
+                                       return ret;
+                               }
                        }
-                       attrs[0] = el->name;
-                       attrs[1] = NULL;
-
-                       /* We need to setup a search, and then setup del as required */
-                       
-                       /* The callback does all the hard work here, acting identically to if we had delted the whole entry */
-                       ret = ldb_build_search_req(&new_req, module->ldb, req,
-                                                  req->op.mod.message->dn, 
-                                                  LDB_SCOPE_BASE,
-                                                  "(objectClass=*)",
-                                                  attrs,
-                                                  NULL, 
-                                                  ac, 
-                                                  linked_attributes_rename_del_search_callback);
+                       break;
 
-                       if (ret != LDB_SUCCESS) {
-                               return ret;
-                       }
-                       
-                       talloc_steal(new_req, attrs);
-                       
-                       ret = ldb_set_timeout_from_prev_req(module->ldb, req, new_req);
-                       
-                       if (ret != LDB_SUCCESS) {
-                               return ret;
-                       }
+               case LDB_FLAG_MOD_DELETE:
 
-                       /* Create a spot in the list for the requests */
-                       ac->down_req = talloc_realloc(ac, ac->down_req, 
-                                                     struct ldb_request *, ac->num_requests + 1);
-                       if (!ac->down_req) {
-                               ldb_oom(ac->module->ldb);
-                               return LDB_ERR_OPERATIONS_ERROR;
+                       if (el->num_values) {
+                               /* For each value being deleted, we need to setup the delete */
+                               for (j = 0; j < el->num_values; j++) {
+                                       ret = la_store_op(ac, LA_OP_DEL,
+                                                 (char *)el->values[j].data,
+                                                         attr_name, attr_val);
+                                       if (ret != LDB_SUCCESS) {
+                                               return ret;
+                                       }
+                               }
+                       } else {
+                               store_el = true;
                        }
 
-                       ac->down_req[ac->num_requests] = talloc_steal(ac->down_req, new_req);
-                       ac->num_requests++;
-                       
-                       ret = ldb_next_request(module, new_req);
-               
-                       if (ret != LDB_SUCCESS) {
-                               return ret;
-                       }
-                       
-                       continue;
+                       break;
                }
 
-               /* Prepare the modify (mod element) on the targets, for a normal modify request */
-
-               /* For each value being moded, we need to setup the modify */
-               for (j=0; j < el->num_values; j++) {
-                       /* Create the modify request */
-                       struct ldb_message *new_msg = ldb_msg_new(ac);
-                       if (!new_msg) {
-                               ldb_oom(module->ldb);
-                               return LDB_ERR_OPERATIONS_ERROR;
-                       }
-                       new_msg->dn = ldb_dn_from_ldb_val(new_msg, module->ldb, &el->values[j]);
-                       if (!new_msg->dn) {
-                               ldb_asprintf_errstring(module->ldb, 
-                                              "attribute %s value %s was not a valid DN", req->op.mod.message->elements[i].name,
-                                                      el->values[j].data);
-                               return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
-                       }
+               if (store_el) {
+                       struct ldb_message_element *search_el;
 
-                       ret = ldb_msg_add_empty(new_msg, target_attr->lDAPDisplayName, 
-                                               el->flags & LDB_FLAG_MOD_MASK, NULL);
-                       if (ret != LDB_SUCCESS) {
-                               return ret;
-                       }
-                       
-                       ret = ldb_msg_add_string(new_msg, target_attr->lDAPDisplayName, 
-                                                ldb_dn_get_linearized(ac->orig_req->op.add.message->dn));
-                       if (ret != LDB_SUCCESS) {
-                               return ret;
+                       if (!ac->rc) {
+                               ac->rc = talloc_zero(ac, struct replace_context);
+                               if (!ac->rc) {
+                                       ldb_oom(module->ldb);
+                                       return LDB_ERR_OPERATIONS_ERROR;
+                               }
                        }
 
-                       ret = ldb_build_mod_req(&new_req, module->ldb, ac,
-                                               new_msg,
-                                               NULL,
-                                               NULL,
-                                               NULL);
-                       if (ret != LDB_SUCCESS) {
-                               return ret;
-                       }
-                       
-                       talloc_steal(new_req, new_msg);
-                       
-                       ret = ldb_set_timeout_from_prev_req(module->ldb, req, new_req);
-                       
-                       if (ret != LDB_SUCCESS) {
-                               return ret;
-                       }
-                       
-                       /* Now add it to the list */
-                       ac->down_req = talloc_realloc(ac, ac->down_req, 
-                                                     struct ldb_request *, ac->num_requests + 1);
-                       if (!ac->down_req) {
-                               ldb_oom(ac->module->ldb);
+                       search_el = talloc_realloc(ac->rc, ac->rc->el,
+                                                  struct ldb_message_element,
+                                                  ac->rc->num_elements +1);
+                       if (!search_el) {
+                               ldb_oom(module->ldb);
                                return LDB_ERR_OPERATIONS_ERROR;
                        }
-                       ac->down_req[ac->num_requests] = talloc_steal(ac->down_req, new_req);
-                       ac->num_requests++;
+                       ac->rc->el = search_el;
 
-                       /* Run the new request */
-                       ret = ldb_next_request(module, new_req);
-                       if (ret != LDB_SUCCESS) {
-                               return ret;
-                       }
+                       ac->rc->el[ac->rc->num_elements] = *el;
+                       ac->rc->num_elements++;
                }
        }
-       return LDB_SUCCESS;
-}
 
-static int linked_attributes_rename_del_search_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares) 
-{
-       struct linked_attributes_context *ac = talloc_get_type(context, struct linked_attributes_context);
-       struct ldb_dn *olddn, *newdn;
-    
-       switch (ac->orig_req->operation) {
-       case LDB_DELETE:
-       {
-               olddn = ac->orig_req->op.del.dn;
-               newdn = NULL;
-               break;
-       } 
-       /* This isn't the general modify case, just the modify when we are asked to delete all values */
-       case LDB_MODIFY:
-       {
-               olddn = ac->orig_req->op.mod.message->dn;
-               newdn = NULL;
-               break;
-       } 
-       case LDB_RENAME:
-       {
-               olddn = ac->orig_req->op.rename.olddn;
-               newdn = ac->orig_req->op.rename.newdn;
-               break;
-       }       
-       default:
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-       
+       /* both replace and delete without values are handled in the callback
+        * after the search on the entry to be modified is performed */
+       if (ac->rc) {
+               const char **attrs;
+
+               attrs = talloc_array(ac->rc, const char *, ac->rc->num_elements +1);
+               if (!attrs) {
+                       ldb_oom(module->ldb);
+                       return LDB_ERR_OPERATIONS_ERROR;
+               }
+               for (i = 0; i < ac->rc->num_elements; i++) {
+                       attrs[i] = ac->rc->el[i].name;
+               }
+               attrs[i] = NULL;
 
-       /* OK, we have one search result here: */
+               /* The callback does all the hard work here */
+               ret = ldb_build_search_req(&search_req, module->ldb, ac,
+                                          req->op.mod.message->dn,
+                                          LDB_SCOPE_BASE,
+                                          "(objectClass=*)", attrs,
+                                          NULL,
+                                          ac, la_mod_search_callback,
+                                          req);
 
-       /* Only entries are interesting, and we only want the olddn */
-       if (ares->type == LDB_REPLY_ENTRY
-           && ldb_dn_compare(ares->message->dn, olddn) == 0) {
-               /* only bother at all if there were some linked attributes found */
-               if (ares->message->num_elements > 0) {
-                       return setup_modifies(ldb, ac, ac,
-                                             ares->message, olddn, newdn);
+               if (ret == LDB_SUCCESS) {
+                       talloc_steal(search_req, attrs);
+
+                       ret = ldb_next_request(module, search_req);
                }
-               talloc_free(ares);
-               return LDB_SUCCESS;
-       } else if (ares->type == LDB_REPLY_ENTRY) {
-               /* Guh?  We only asked for this DN */
-               return LDB_ERR_OPERATIONS_ERROR;
 
        } else {
-               talloc_free(ares);
-               return LDB_SUCCESS;
+               if (ac->ops) {
+                       /* start the mod requests chain */
+                       ret = la_do_mod_request(ac);
+               } else {
+                       /* nothing to do for this module, proceed */
+                       talloc_free(ac);
+                       ret = ldb_next_request(module, req);
+               }
        }
-       
-       
+
+       return ret;
 }
-/* rename */
-static int linked_attributes_rename(struct ldb_module *module, struct ldb_request *req)
+
+/* delete, rename */
+static int linked_attributes_op(struct ldb_module *module, struct ldb_request *req)
 {
-       /* Look up list of linked attributes */
+       struct ldb_request *search_req;
+       struct ldb_dn *base_dn;
+       struct la_context *ac;
        const char **attrs;
        WERROR werr;
        int ret;
-       struct linked_attributes_context *ac;
-       struct ldb_request *new_req;
-       const struct dsdb_schema *schema = dsdb_get_schema(module->ldb);
-       if (!schema) {
-               /* without schema, this doesn't make any sense */
-               return ldb_next_request(module, req);
-       }
 
        /* This gets complex:  We need to:
-          - Do a search for the entry 
+          - Do a search for the entry
           - Wait for these result to appear
-          - In the callback for the result, issue a modify request based on the linked attributes found
+          - In the callback for the result, issue a modify
+               request based on the linked attributes found
           - Wait for each modify result
-          - Regain our sainity 
+          - Regain our sainity
        */
 
-       ac = linked_attributes_init_handle(req, module);
+       switch (req->operation) {
+       case LDB_RENAME:
+               base_dn = req->op.rename.olddn;
+               break;
+       case LDB_DELETE:
+               base_dn = req->op.del.dn;
+               break;
+       default:
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       ac = linked_attributes_init(module, req);
        if (!ac) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       
-       werr = dsdb_linked_attribute_lDAPDisplayName_list(schema, ac, &attrs);
+
+       if (!ac->schema) {
+               /* without schema, this doesn't make any sense */
+               return ldb_next_request(module, req);
+       }
+
+       werr = dsdb_linked_attribute_lDAPDisplayName_list(ac->schema, ac, &attrs);
        if (!W_ERROR_IS_OK(werr)) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       
-       ret = ldb_build_search_req(&new_req, module->ldb, req,
-                                  req->op.rename.olddn, 
-                                  LDB_SCOPE_BASE,
-                                  "(objectClass=*)",
-                                  attrs,
-                                  NULL, 
-                                  ac, 
-                                  linked_attributes_rename_del_search_callback);
+
+       ret = ldb_build_search_req(&search_req, module->ldb, req,
+                                  base_dn, LDB_SCOPE_BASE,
+                                  "(objectClass=*)", attrs,
+                                  NULL,
+                                  ac, la_op_search_callback,
+                                  req);
 
        if (ret != LDB_SUCCESS) {
                return ret;
        }
 
-       talloc_steal(new_req, attrs);
+       talloc_steal(search_req, attrs);
 
-       ret = ldb_set_timeout_from_prev_req(module->ldb, req, new_req);
+       return ldb_next_request(module, search_req);
+}
 
-       if (ret != LDB_SUCCESS) {
-               return ret;
+static int la_op_search_callback(struct ldb_request *req,
+                                struct ldb_reply *ares)
+{
+       struct la_context *ac;
+       const struct dsdb_attribute *schema_attr;
+       const struct dsdb_attribute *target_attr;
+       const struct ldb_message_element *el;
+       const char *attr_name;
+       const char *deldn;
+       const char *adddn;
+       int i, j;
+       int ret;
+
+       ac = talloc_get_type(req->context, struct la_context);
+
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
+
+       /* Only entries are interesting, and we only want the olddn */
+       switch (ares->type) {
+       case LDB_REPLY_ENTRY:
+               ret = ldb_dn_compare(ares->message->dn, req->op.search.base);
+               if (ret != 0) {
+                       /* Guh?  We only asked for this DN */
+                       talloc_free(ares);
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
+               }
+               if (ares->message->num_elements == 0) {
+                       /* only bother at all if there were some
+                        * linked attributes found */
+                       talloc_free(ares);
+                       return LDB_SUCCESS;
+               }
+
+               switch (ac->req->operation) {
+               case LDB_DELETE:
+                       deldn = ldb_dn_get_linearized(ac->req->op.del.dn);
+                       adddn = NULL;
+                       break;
+               case LDB_RENAME:
+                       deldn = ldb_dn_get_linearized(ac->req->op.rename.olddn);
+                       adddn = ldb_dn_get_linearized(ac->req->op.rename.newdn);
+                       break;
+               default:
+                       talloc_free(ares);
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
+               }
+
+               for (i = 0; i < ares->message->num_elements; i++) {
+                       el = &ares->message->elements[i];
+
+                       schema_attr = dsdb_attribute_by_lDAPDisplayName(ac->schema, el->name);
+                       if (!schema_attr) {
+                               ldb_asprintf_errstring(ac->module->ldb,
+                                       "attribute %s is not a valid attribute"
+                                       " in schema", el->name);
+                               talloc_free(ares);
+                               return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OBJECT_CLASS_VIOLATION);
+                       }
+
+                       /* Valid attribute, now find out if it is linked */
+                       if (schema_attr->linkID == 0) {
+                               /* Not a linked attribute, skip */
+                               continue;
+                       }
+
+                       if ((schema_attr->linkID & 1) == 0) {
+                               /* Odd is for the target. */
+                               target_attr = dsdb_attribute_by_linkID(ac->schema, schema_attr->linkID + 1);
+                               if (!target_attr) {
+                                       continue;
+                               }
+                               attr_name = target_attr->lDAPDisplayName;
+                       } else {
+                               target_attr = dsdb_attribute_by_linkID(ac->schema, schema_attr->linkID - 1);
+                               if (!target_attr) {
+                                       continue;
+                               }
+                               attr_name = target_attr->lDAPDisplayName;
+                       }
+                       for (j = 0; j < el->num_values; j++) {
+                               ret = la_store_op(ac, LA_OP_DEL,
+                                         (char *)el->values[j].data,
+                                                 attr_name, deldn);
+                               if (ret != LDB_SUCCESS) {
+                                       talloc_free(ares);
+                                       return ldb_module_done(ac->req,
+                                                              NULL, NULL, ret);
+                               }
+                               if (!adddn) continue;
+                               ret = la_store_op(ac, LA_OP_ADD,
+                                         (char *)el->values[j].data,
+                                                 attr_name, adddn);
+                               if (ret != LDB_SUCCESS) {
+                                       talloc_free(ares);
+                                       return ldb_module_done(ac->req,
+                                                              NULL, NULL, ret);
+                               }
+                       }
+               }
+
+               break;
+
+       case LDB_REPLY_REFERRAL:
+               /* ignore */
+               break;
+
+       case LDB_REPLY_DONE:
+
+               talloc_free(ares);
+
+               if (ac->ops) {
+                       /* start the mod requests chain */
+                       ret = la_do_mod_request(ac);
+               } else {
+                       ret = la_down_req(ac);
+               }
+               if (ret != LDB_SUCCESS) {
+                       return ldb_module_done(ac->req, NULL, NULL, ret);
+               }
+               return LDB_SUCCESS;
        }
 
-       ac->search_req = new_req;
-       ac->step = LA_SEARCH;
-       return ldb_next_request(module, new_req);
+       talloc_free(ares);
+       return LDB_SUCCESS;
 }
 
-/* delete */
-static int linked_attributes_delete(struct ldb_module *module, struct ldb_request *req)
+/* do a linked attributes modify request */
+static int la_do_mod_request(struct la_context *ac)
 {
-       /* Look up list of linked attributes */
-       const char **attrs;
-       WERROR werr;
+       struct ldb_message_element *ret_el;
+       struct ldb_request *mod_req;
+       struct ldb_message *new_msg;
+       struct ldb_context *ldb;
        int ret;
-       struct ldb_request *new_req;
-       struct linked_attributes_context *ac;
-       const struct dsdb_schema *schema = dsdb_get_schema(module->ldb);
-       if (!schema) {
-               /* without schema, this doesn't make any sense */
-               return ldb_next_request(module, req);
-       }
 
-       /* This gets complex:  We need to:
-          - Do a search for the entry 
-          - Wait for these result to appear
-          - In the callback for the result, issue a modify request based on the linked attributes found
-          - Wait for each modify result
-          - Regain our sainity 
-       */
+       ldb = ac->module->ldb;
 
-       ac = linked_attributes_init_handle(req, module);
-       if (!ac) {
+       /* Create the modify request */
+       new_msg = ldb_msg_new(ac);
+       if (!new_msg) {
+               ldb_oom(ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       
-       werr = dsdb_linked_attribute_lDAPDisplayName_list(schema, ac, &attrs);
-       if (!W_ERROR_IS_OK(werr)) {
+       new_msg->dn = ldb_dn_copy(new_msg, ac->ops->dn);
+       if (!new_msg->dn) {
                return LDB_ERR_OPERATIONS_ERROR;
-       };
-       
-       ret = ldb_build_search_req(&new_req, module->ldb, req,
-                                  req->op.del.dn, 
-                                  LDB_SCOPE_BASE,
-                                  "(objectClass=*)",
-                                  attrs,
-                                  NULL, 
-                                  ac, 
-                                  linked_attributes_rename_del_search_callback);
+       }
 
+       if (ac->ops->op == LA_OP_ADD) {
+               ret = ldb_msg_add_empty(new_msg, ac->ops->name,
+                                       LDB_FLAG_MOD_ADD, &ret_el);
+       } else {
+               ret = ldb_msg_add_empty(new_msg, ac->ops->name,
+                                       LDB_FLAG_MOD_DELETE, &ret_el);
+       }
        if (ret != LDB_SUCCESS) {
                return ret;
        }
-
-       talloc_steal(new_req, attrs);
-
-       ret = ldb_set_timeout_from_prev_req(module->ldb, req, new_req);
-
+       ret_el->values = talloc_array(new_msg, struct ldb_val, 1);
+       if (!ret_el->values) {
+               ldb_oom(ldb);
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+       ret_el->values[0] = data_blob_string_const(ac->ops->value);
+       ret_el->num_values = 1;
+
+       /* use ac->ops as the mem_ctx so that the request will be freed
+        * in the callback as soon as completed */
+       ret = ldb_build_mod_req(&mod_req, ldb, ac->ops,
+                               new_msg,
+                               NULL,
+                               ac, la_mod_callback,
+                               ac->req);
        if (ret != LDB_SUCCESS) {
                return ret;
        }
+       talloc_steal(mod_req, new_msg);
 
-       ac->search_req = new_req;
-       ac->step = LA_SEARCH;
-       return ldb_next_request(module, new_req);
+       /* Run the new request */
+       return ldb_next_request(ac->module, mod_req);
 }
 
+static int la_mod_callback(struct ldb_request *req, struct ldb_reply *ares)
+{
+       struct la_context *ac;
+       struct la_op_store *os;
+       int ret;
 
-static int linked_attributes_wait_none(struct ldb_handle *handle) {
-       struct linked_attributes_context *ac;
-       int i, ret = LDB_ERR_OPERATIONS_ERROR;
-       if (!handle || !handle->private_data) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
+       ac = talloc_get_type(req->context, struct la_context);
 
-       if (handle->state == LDB_ASYNC_DONE) {
-               return handle->status;
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
        }
 
-       handle->state = LDB_ASYNC_PENDING;
-       handle->status = LDB_SUCCESS;
-
-       ac = talloc_get_type(handle->private_data, struct linked_attributes_context);
-
-       switch (ac->step) {
-       case LA_SEARCH:
-               ret = ldb_wait(ac->search_req->handle, LDB_WAIT_NONE);
-               
-               if (ret != LDB_SUCCESS) {
-                       handle->status = ret;
-                       goto done;
-               }
-               if (ac->search_req->handle->status != LDB_SUCCESS) {
-                       handle->status = ac->search_req->handle->status;
-                       goto done;
-               }
-               
-               if (ac->search_req->handle->state != LDB_ASYNC_DONE) {
-                       return LDB_SUCCESS;
-               }
-               ac->step = LA_DO_OPS;
-               return LDB_SUCCESS;
+       if (ares->type != LDB_REPLY_DONE) {
+               ldb_set_errstring(ac->module->ldb,
+                                 "invalid ldb_reply_type in callback");
+               talloc_free(ares);
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
 
-       case LA_DO_OPS:
-               for (i=0; i < ac->num_requests; i++) {
-                       ret = ldb_wait(ac->down_req[i]->handle, LDB_WAIT_NONE);
-                       
-                       if (ret != LDB_SUCCESS) {
-                               handle->status = ret;
-                               goto done;
-                       }
-                       if (ac->down_req[i]->handle->status != LDB_SUCCESS) {
-                               handle->status = ac->down_req[i]->handle->status;
-                               goto done;
-                       }
-                       
-                       if (ac->down_req[i]->handle->state != LDB_ASYNC_DONE) {
-                               return LDB_SUCCESS;
-                       }
-               }
+       talloc_free(ares);
 
-               /* Now run the original request */
-               ac->step = LA_DO_ORIG;
-               return ldb_next_request(ac->module, ac->orig_down_req);
+       if (ac->ops) {
+               os = ac->ops;
+               ac->ops = os->next;
 
-       case LA_DO_ORIG:
-               ret = ldb_wait(ac->orig_down_req->handle, LDB_WAIT_NONE);
-               
-               if (ret != LDB_SUCCESS) {
-                       handle->status = ret;
-                       goto done;
-               }
-               if (ac->orig_down_req->handle->status != LDB_SUCCESS) {
-                       handle->status = ac->orig_down_req->handle->status;
-                       goto done;
-               }
-               
-               if (ac->orig_down_req->handle->state != LDB_ASYNC_DONE) {
-                       return LDB_SUCCESS;
-               }
-               ret = LDB_SUCCESS;
+               /* this frees the request too
+                * DO NOT access 'req' after this point */
+               talloc_free(os);
        }
 
-done:
-       handle->state = LDB_ASYNC_DONE;
-       return ret;
+       /* as last op run the original request */
+       if (ac->ops) {
+               ret = la_do_mod_request(ac);
+       } else {
+               ret = la_down_req(ac);
+       }
 
+       if (ret != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, NULL, NULL, ret);
+       }
+       return LDB_SUCCESS;
 }
 
-static int linked_attributes_wait_all(struct ldb_handle *handle) {
-
+static int la_down_req(struct la_context *ac)
+{
+       struct ldb_request *down_req;
        int ret;
 
-       while (handle->state != LDB_ASYNC_DONE) {
-               ret = linked_attributes_wait_none(handle);
-               if (ret != LDB_SUCCESS) {
-                       return ret;
-               }
+       switch (ac->req->operation) {
+       case LDB_ADD:
+               ret = ldb_build_add_req(&down_req, ac->module->ldb, ac,
+                                       ac->req->op.add.message,
+                                       ac->req->controls,
+                                       ac, la_down_callback,
+                                       ac->req);
+               break;
+       case LDB_MODIFY:
+               ret = ldb_build_mod_req(&down_req, ac->module->ldb, ac,
+                                       ac->req->op.mod.message,
+                                       ac->req->controls,
+                                       ac, la_down_callback,
+                                       ac->req);
+               break;
+       case LDB_DELETE:
+               ret = ldb_build_del_req(&down_req, ac->module->ldb, ac,
+                                       ac->req->op.del.dn,
+                                       ac->req->controls,
+                                       ac, la_down_callback,
+                                       ac->req);
+               break;
+       case LDB_RENAME:
+               ret = ldb_build_rename_req(&down_req, ac->module->ldb, ac,
+                                          ac->req->op.rename.olddn,
+                                          ac->req->op.rename.newdn,
+                                          ac->req->controls,
+                                          ac, la_down_callback,
+                                          ac->req);
+               break;
+       default:
+               ret = LDB_ERR_OPERATIONS_ERROR;
+       }
+       if (ret != LDB_SUCCESS) {
+               return ret;
        }
 
-       return handle->status;
+       return ldb_next_request(ac->module, down_req);
 }
 
-static int linked_attributes_wait(struct ldb_handle *handle, enum ldb_wait_type type)
+static int la_down_callback(struct ldb_request *req, struct ldb_reply *ares)
 {
-       if (type == LDB_WAIT_ALL) {
-               return linked_attributes_wait_all(handle);
-       } else {
-               return linked_attributes_wait_none(handle);
+       struct la_context *ac;
+
+       ac = talloc_get_type(req->context, struct la_context);
+
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
+
+       if (ares->type != LDB_REPLY_DONE) {
+               ldb_set_errstring(ac->module->ldb,
+                                 "invalid ldb_reply_type in callback");
+               talloc_free(ares);
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
        }
+
+       return ldb_module_done(ac->req, ares->controls,
+                               ares->response, ares->error);
 }
 
 _PUBLIC_ const struct ldb_module_ops ldb_linked_attributes_module_ops = {
        .name              = "linked_attributes",
        .add               = linked_attributes_add,
        .modify            = linked_attributes_modify,
-       .del               = linked_attributes_delete,
-       .rename            = linked_attributes_rename,
-       .wait              = linked_attributes_wait,
+       .del               = linked_attributes_op,
+       .rename            = linked_attributes_op,
 };
index a411c015133df8165ef457f27a9ac074f14dfc7c..622e44416634e6301aa730a0cda1d3ae4ca2e7c8 100644 (file)
@@ -1,7 +1,7 @@
 /* 
    ldb database module
 
-   Copyright (C) Simo Sorce  2004-2006
+   Copyright (C) Simo Sorce  2004-2008
    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005-2006
    Copyright (C) Andrew Tridgell 2004
 
@@ -44,7 +44,7 @@
    This allows the password database to be syncronised in a multi-master
    fashion, seperate to the more difficult concerns of the main
    database.  (With passwords, the last writer always wins)
-   
+
    Each incoming add/modify is split into a remote, and a local request, done in that order.
 
    We maintain a list of attributes that are kept locally:
@@ -62,73 +62,89 @@ static const char * const password_attrs[] = {
 
 /* And we merge them back into search requests when asked to do so */
 
-struct lpdb_context {
+struct lpdb_reply {
+       struct lpdb_reply *next;
+       struct ldb_reply *remote;
+       struct ldb_dn *local_dn;
+};
 
-       enum lpdb_type {LPDB_ADD, LPDB_MOD, LPDB_SEARCH} type;
-       enum lpdb_step {LPDB_ADD_REMOTE, LPDB_MOD_REMOTE, LPDB_MOD_SEARCH_SELF, LPDB_LOCAL, LPDB_SEARCH_REMOTE} step;
+struct lpdb_context {
 
        struct ldb_module *module;
-       struct ldb_request *orig_req;
-       struct ldb_request *remote_req;
-       struct ldb_request *search_req;
-       struct ldb_request *local_req;
+       struct ldb_request *req;
 
        struct ldb_message *local_message;
 
+       struct lpdb_reply *list;
+       struct lpdb_reply *current;
+       struct ldb_reply *remote_done;
+       struct ldb_reply *remote;
+
        bool added_objectGUID;
        bool added_objectClass;
 
-       struct ldb_reply *search_res;
-};
-
-struct lpdb_local_search_context {
-       struct lpdb_context *ac;
-       struct ldb_reply *remote_res;
-       struct ldb_reply *local_res;
 };
 
-static struct ldb_handle *lpdb_init_handle(struct ldb_request *req, struct ldb_module *module, enum lpdb_type type)
+static struct lpdb_context *lpdb_init_context(struct ldb_module *module,
+                                             struct ldb_request *req)
 {
        struct lpdb_context *ac;
-       struct ldb_handle *h;
 
-       h = talloc_zero(req, struct ldb_handle);
-       if (h == NULL) {
+       ac = talloc_zero(req, struct lpdb_context);
+       if (ac == NULL) {
                ldb_set_errstring(module->ldb, "Out of Memory");
                return NULL;
        }
 
-       h->module = module;
+       ac->module = module;
+       ac->req = req;
 
-       ac = talloc_zero(h, struct lpdb_context);
-       if (ac == NULL) {
-               ldb_set_errstring(module->ldb, "Out of Memory");
-               talloc_free(h);
-               return NULL;
-       }
+       return ac;
+}
 
-       h->private_data = (void *)ac;
+static int lpdb_local_callback(struct ldb_request *req, struct ldb_reply *ares)
+{
+       struct lpdb_context *ac;
 
-       h->state = LDB_ASYNC_INIT;
-       h->status = LDB_SUCCESS;
+       ac = talloc_get_type(req->context, struct lpdb_context);
 
-       ac->type = type;
-       ac->module = module;
-       ac->orig_req = req;
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
+
+       if (ares->type != LDB_REPLY_DONE) {
+               ldb_set_errstring(ac->module->ldb, "Unexpected reply type");
+               talloc_free(ares);
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
 
-       return h;
+       talloc_free(ares);
+       return ldb_module_done(ac->req,
+                               ac->remote_done->controls,
+                               ac->remote_done->response,
+                               ac->remote_done->error);
 }
 
-/* Add a record, splitting password attributes from the user's main
- * record */
+/*****************************************************************************
+ * ADD
+ ****************************************************************************/
+
+static int lpdb_add_callback(struct ldb_request *req,
+                               struct ldb_reply *ares);
 
 static int local_password_add(struct ldb_module *module, struct ldb_request *req)
 {
-       struct ldb_handle *h;
-       struct lpdb_context *ac;
        struct ldb_message *remote_message;
-       struct ldb_message *local_message;
+       struct ldb_request *remote_req;
+       struct lpdb_context *ac;
        struct GUID objectGUID;
+       int ret;
        int i;
 
        ldb_debug(module->ldb, LDB_DEBUG_TRACE, "local_password_add\n");
@@ -163,22 +179,12 @@ static int local_password_add(struct ldb_module *module, struct ldb_request *req
        }
 
        /* From here, we assume we have password attributes to split off */
-       h = lpdb_init_handle(req, module, LPDB_ADD);
-       if (!h) {
+       ac = lpdb_init_context(module, req);
+       if (!ac) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       ac = talloc_get_type(h->private_data, struct lpdb_context);
 
-       ac->orig_req = req;
-
-       ac->remote_req = talloc(ac, struct ldb_request);
-       if (ac->remote_req == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       *(ac->remote_req) = *(ac->orig_req);
-
-       remote_message = ldb_msg_copy_shallow(ac->remote_req, ac->orig_req->op.add.message);
+       remote_message = ldb_msg_copy_shallow(remote_req, req->op.add.message);
        if (remote_message == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
@@ -188,81 +194,113 @@ static int local_password_add(struct ldb_module *module, struct ldb_request *req
                ldb_msg_remove_attr(remote_message, password_attrs[i]);
        }
 
-       ac->remote_req->op.add.message = remote_message;
-
-       ac->remote_req->context = NULL;
-       ac->remote_req->callback = NULL;
-
-       ac->local_req = talloc(ac, struct ldb_request);
-       if (ac->local_req == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
+       /* Find the objectGUID to use as the key */
+       objectGUID = samdb_result_guid(ac->req->op.add.message, "objectGUID");
 
-       *(ac->local_req) = *(ac->orig_req);
-       local_message = ldb_msg_copy_shallow(ac->local_req, ac->orig_req->op.add.message);
-       if (local_message == NULL) {
+       ac->local_message = ldb_msg_copy_shallow(ac, req->op.add.message);
+       if (ac->local_message == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
        /* Remove anything seen in the remote message from the local
         * message (leaving only password attributes) */
-       for (i=0;i<ac->remote_req->op.add.message->num_elements;i++) {
-               ldb_msg_remove_attr(local_message, ac->remote_req->op.add.message->elements[i].name);
+       for (i=0; i < remote_message->num_elements; i++) {
+               ldb_msg_remove_attr(ac->local_message, remote_message->elements[i].name);
        }
 
        /* We must have an objectGUID already, or we don't know where
         * to add the password.  This may be changed to an 'add and
         * search', to allow the directory to create the objectGUID */
-       if (ldb_msg_find_ldb_val(ac->orig_req->op.add.message, "objectGUID") == NULL) {
-               ldb_set_errstring(module->ldb, 
-                                 "no objectGUID found in search: local_password module must be configured below objectGUID module!\n");
+       if (ldb_msg_find_ldb_val(req->op.add.message, "objectGUID") == NULL) {
+               ldb_set_errstring(module->ldb,
+                                 "no objectGUID found in search: "
+                                 "local_password module must be "
+                                 "onfigured below objectGUID module!\n");
                return LDB_ERR_CONSTRAINT_VIOLATION;
        }
 
-       /* Find the objectGUID to use as the key */
-       objectGUID = samdb_result_guid(ac->orig_req->op.add.message, "objectGUID");
-       
-       local_message->dn = ldb_dn_new(local_message, module->ldb, LOCAL_BASE);
-       ldb_dn_add_child_fmt(local_message->dn, PASSWORD_GUID_ATTR "=%s", GUID_string(local_message, &objectGUID));
-
-       ac->local_req->op.add.message = local_message;
-
-       ac->local_req->context = NULL;
-       ac->local_req->callback = NULL;
-
-       ac->step = LPDB_ADD_REMOTE;
+       ac->local_message->dn = ldb_dn_new(ac->local_message,
+                                          module->ldb, LOCAL_BASE);
+       if ((ac->local_message->dn == NULL) ||
+           ( ! ldb_dn_add_child_fmt(ac->local_message->dn,
+                                    PASSWORD_GUID_ATTR "=%s",
+                                    GUID_string(ac->local_message,
+                                                       &objectGUID)))) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
 
-       /* Return our own handle do deal with this call */
-       req->handle = h;
+       ret = ldb_build_add_req(&remote_req, module->ldb, ac,
+                               remote_message,
+                               req->controls,
+                               ac, lpdb_add_callback,
+                               req);
+       if (ret != LDB_SUCCESS) {
+               return ret;
+       }
 
-       return ldb_next_request(module, ac->remote_req);
+       return ldb_next_request(module, remote_req);
 }
 
-/* After adding the remote entry, add the local one */
-static int local_password_add_local(struct ldb_handle *h) {
-
+/* Add a record, splitting password attributes from the user's main
+ * record */
+static int lpdb_add_callback(struct ldb_request *req,
+                               struct ldb_reply *ares)
+{
+       struct ldb_request *local_req;
        struct lpdb_context *ac;
-       ac = talloc_get_type(h->private_data, struct lpdb_context);
+       int ret;
+
+       ac = talloc_get_type(req->context, struct lpdb_context);
 
-       h->state = LDB_ASYNC_INIT;
-       h->status = LDB_SUCCESS;
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
 
-       ac->step = LPDB_LOCAL;
+       if (ares->type != LDB_REPLY_DONE) {
+               ldb_set_errstring(ac->module->ldb, "Unexpected reply type");
+               talloc_free(ares);
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
 
-       ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->local_req);
+       ac->remote_done = talloc_steal(ac, ares);
 
-       /* perform the local add */
-       return ldb_next_request(ac->module, ac->local_req);
+       ret = ldb_build_add_req(&local_req, ac->module->ldb, ac,
+                               ac->local_message,
+                               NULL,
+                               ac, lpdb_local_callback,
+                               ac->req);
+       if (ret != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, NULL, NULL, ret);
+       }
+
+       ret = ldb_next_request(ac->module, local_req);
+       if (ret != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, NULL, NULL, ret);
+       }
+       return LDB_SUCCESS;
 }
 
-static int local_password_mod_search_self(struct ldb_handle *h);
+/*****************************************************************************
+ * MODIFY
+ ****************************************************************************/
+
+static int lpdb_modify_callabck(struct ldb_request *req,
+                               struct ldb_reply *ares);
+static int lpdb_mod_search_callback(struct ldb_request *req,
+                                   struct ldb_reply *ares);
 
 static int local_password_modify(struct ldb_module *module, struct ldb_request *req)
 {
-       struct ldb_handle *h;
        struct lpdb_context *ac;
        struct ldb_message *remote_message;
-       struct ldb_message *local_message;
+       struct ldb_request *remote_req;
+       int ret;
        int i;
 
        ldb_debug(module->ldb, LDB_DEBUG_TRACE, "local_password_modify\n");
@@ -289,243 +327,565 @@ static int local_password_modify(struct ldb_module *module, struct ldb_request *
        }
 
        /* From here, we assume we have password attributes to split off */
-       h = lpdb_init_handle(req, module, LPDB_MOD);
-       if (!h) {
+       ac = lpdb_init_context(module, req);
+       if (!ac) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       ac = talloc_get_type(h->private_data, struct lpdb_context);
 
-       ac->orig_req = req;
-
-       ac->remote_req = talloc(ac, struct ldb_request);
-       if (ac->remote_req == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       *(ac->remote_req) = *(ac->orig_req);
-       remote_message = ldb_msg_copy_shallow(ac->remote_req, ac->orig_req->op.mod.message);
+       remote_message = ldb_msg_copy_shallow(ac, ac->req->op.mod.message);
        if (remote_message == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       
+
        /* Remove any password attributes from the remote message */
        for (i=0; i < ARRAY_SIZE(password_attrs); i++) {
                ldb_msg_remove_attr(remote_message, password_attrs[i]);
        }
 
-       ac->remote_req->op.mod.message = remote_message;
-
-       ac->remote_req->context = NULL;
-       ac->remote_req->callback = NULL;
-
-       ac->local_req = talloc(ac, struct ldb_request);
-       if (ac->local_req == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       *(ac->local_req) = *(ac->orig_req);
-       local_message = ldb_msg_copy_shallow(ac->local_req, ac->orig_req->op.mod.message);
-       if (local_message == NULL) {
+       ac->local_message = ldb_msg_copy_shallow(ac, ac->req->op.mod.message);
+       if (ac->local_message == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
        /* Remove anything seen in the remote message from the local
         * message (leaving only password attributes) */
-       for (i=0;i<ac->remote_req->op.mod.message->num_elements;i++) {
-               ldb_msg_remove_attr(local_message, ac->remote_req->op.mod.message->elements[i].name);
+       for (i=0; i < remote_message->num_elements;i++) {
+               ldb_msg_remove_attr(ac->local_message, remote_message->elements[i].name);
        }
 
-       ac->local_req->op.mod.message = local_message;
-       ac->local_message = local_message;
+       ret = ldb_build_mod_req(&remote_req, module->ldb, ac,
+                               remote_message,
+                               req->controls,
+                               ac, lpdb_modify_callabck,
+                               req);
+       if (ret != LDB_SUCCESS) {
+               return ret;
+       }
 
-       ac->local_req->context = NULL;
-       ac->local_req->callback = NULL;
+       return ldb_next_request(module, remote_req);
+}
 
-       ac->step = LPDB_MOD_REMOTE;
+/* On a modify, we don't have the objectGUID handy, so we need to
+ * search our DN for it */
+static int lpdb_modify_callabck(struct ldb_request *req,
+                               struct ldb_reply *ares)
+{
+       static const char * const attrs[] = { "objectGUID", "objectClass", NULL };
+       struct ldb_request *search_req;
+       struct lpdb_context *ac;
+       int ret;
+
+       ac = talloc_get_type(req->context, struct lpdb_context);
+
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
+
+       if (ares->type != LDB_REPLY_DONE) {
+               ldb_set_errstring(ac->module->ldb, "Unexpected reply type");
+               talloc_free(ares);
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+
+       ac->remote_done = talloc_steal(ac, ares);
 
-       /* Return our own handle do deal with this call */
-       req->handle = h;
+       /* prepare the search operation */
+       ret = ldb_build_search_req(&search_req, ac->module->ldb, ac,
+                                  ac->req->op.mod.message->dn, LDB_SCOPE_BASE,
+                                  "(objectclass=*)", attrs,
+                                  NULL,
+                                  ac, lpdb_mod_search_callback,
+                                  ac->req);
+       if (ret != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
 
-       return ldb_next_request(module, ac->remote_req);
+       ret = ldb_next_request(ac->module, search_req);
+       if (ret != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       return LDB_SUCCESS;
 }
 
-/* Called when we search for our oen entry.  Stores the one entry we
+/* Called when we search for our own entry.  Stores the one entry we
  * expect (as it is a base search) on the context pointer */
-static int get_self_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares)
+static int lpdb_mod_search_callback(struct ldb_request *req,
+                                   struct ldb_reply *ares)
 {
+       struct ldb_request *local_req;
        struct lpdb_context *ac;
+       struct ldb_dn *local_dn;
+       struct GUID objectGUID;
+       int ret = LDB_SUCCESS;
 
-       ac = talloc_get_type(context, struct lpdb_context);
+       ac = talloc_get_type(req->context, struct lpdb_context);
+
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
 
-       /* we are interested only in the single reply (base search) we receive here */
-       if (ares->type == LDB_REPLY_ENTRY) {
-               if (ac->search_res != NULL) {
-                       ldb_set_errstring(ldb, "Too many results");
+       switch (ares->type) {
+       case LDB_REPLY_ENTRY:
+               if (ac->remote != NULL) {
+                       ldb_set_errstring(ac->module->ldb, "Too many results");
                        talloc_free(ares);
-                       return LDB_ERR_OPERATIONS_ERROR;
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
                }
 
-               ac->search_res = talloc_steal(ac, ares);
-       } else {
+               ac->remote = talloc_steal(ac, ares);
+               break;
+
+       case LDB_REPLY_REFERRAL:
+
+               /* ignore */
+               talloc_free(ares);
+               break;
+
+       case LDB_REPLY_DONE:
+               /* After we find out the objectGUID for the entry, modify the local
+                * password database as required */
+
                talloc_free(ares);
+
+               /* if it is not an entry of type person this is an error */
+               /* TODO: remove this when sambaPassword will be in schema */
+               if (ac->remote == NULL) {
+                       ldb_asprintf_errstring(ac->module->ldb,
+                               "entry just modified (%s) not found!",
+                               ldb_dn_get_linearized(req->op.search.base));
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
+               }
+               if (!ldb_msg_check_string_attribute(ac->remote->message,
+                                                   "objectClass", "person")) {
+                       /* Not relevent to us */
+                       return ldb_module_done(ac->req,
+                                               ac->remote_done->controls,
+                                               ac->remote_done->response,
+                                               ac->remote_done->error);
+               }
+
+               if (ldb_msg_find_ldb_val(ac->remote->message,
+                                        "objectGUID") == NULL) {
+                       ldb_set_errstring(ac->module->ldb,
+                                         "no objectGUID found in search: "
+                                         "local_password module must be "
+                                         "configured below objectGUID "
+                                         "module!\n");
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OBJECT_CLASS_VIOLATION);
+               }
+
+               objectGUID = samdb_result_guid(ac->remote->message,
+                                               "objectGUID");
+
+               local_dn = ldb_dn_new(ac, ac->module->ldb, LOCAL_BASE);
+               if ((local_dn == NULL) ||
+                   ( ! ldb_dn_add_child_fmt(local_dn,
+                                           PASSWORD_GUID_ATTR "=%s",
+                                           GUID_string(ac, &objectGUID)))) {
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
+               }
+               ac->local_message->dn = local_dn;
+
+               ret = ldb_build_mod_req(&local_req, ac->module->ldb, ac,
+                                       ac->local_message,
+                                       NULL,
+                                       ac, lpdb_local_callback,
+                                       ac->req);
+               if (ret != LDB_SUCCESS) {
+                       return ldb_module_done(ac->req, NULL, NULL, ret);
+               }
+
+               /* perform the local update */
+               ret = ldb_next_request(ac->module, local_req);
+               if (ret != LDB_SUCCESS) {
+                       return ldb_module_done(ac->req, NULL, NULL, ret);
+               }
        }
 
        return LDB_SUCCESS;
 }
 
-/* On a modify, we don't have the objectGUID handy, so we need to
- * search our DN for it */
-static int local_password_mod_search_self(struct ldb_handle *h) {
+/*****************************************************************************
+ * DELETE
+ ****************************************************************************/
 
+static int lpdb_delete_callabck(struct ldb_request *req,
+                               struct ldb_reply *ares);
+static int lpdb_del_search_callback(struct ldb_request *req,
+                                   struct ldb_reply *ares);
+
+static int local_password_delete(struct ldb_module *module,
+                                struct ldb_request *req)
+{
+       struct ldb_request *remote_req;
        struct lpdb_context *ac;
-       static const char * const attrs[] = { "objectGUID", "objectClass", NULL };
+       int ret;
 
-       ac = talloc_get_type(h->private_data, struct lpdb_context);
+       ldb_debug(module->ldb, LDB_DEBUG_TRACE, "local_password_delete\n");
 
-       /* prepare the search operation */
-       ac->search_req = talloc_zero(ac, struct ldb_request);
-       if (ac->search_req == NULL) {
-               ldb_debug(ac->module->ldb, LDB_DEBUG_ERROR, "Out of Memory!\n");
-               return LDB_ERR_OPERATIONS_ERROR;
+       /* do not manipulate our control entries */
+       if (ldb_dn_is_special(req->op.mod.message->dn)) {
+               return ldb_next_request(module, req);
+       }
+
+       /* If the caller is manipulating the local passwords directly,
+        * let them pass */
+       if (ldb_dn_compare_base(ldb_dn_new(req, module->ldb, LOCAL_BASE),
+                               req->op.del.dn) == 0) {
+               return ldb_next_request(module, req);
        }
 
-       ac->search_req->operation = LDB_SEARCH;
-       ac->search_req->op.search.base = ac->orig_req->op.mod.message->dn;
-       ac->search_req->op.search.scope = LDB_SCOPE_BASE;
-       ac->search_req->op.search.tree = ldb_parse_tree(ac->orig_req, NULL);
-       if (ac->search_req->op.search.tree == NULL) {
-               ldb_set_errstring(ac->module->ldb, "Invalid search filter");
+       /* From here, we assume we have password attributes to split off */
+       ac = lpdb_init_context(module, req);
+       if (!ac) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       ac->search_req->op.search.attrs = attrs;
-       ac->search_req->controls = NULL;
-       ac->search_req->context = ac;
-       ac->search_req->callback = get_self_callback;
-       ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->search_req);
 
-       ac->step = LPDB_MOD_SEARCH_SELF;
+       ret = ldb_build_del_req(&remote_req, module->ldb, ac,
+                               req->op.del.dn,
+                               req->controls,
+                               ac, lpdb_delete_callabck,
+                               req);
+       if (ret != LDB_SUCCESS) {
+               return ret;
+       }
 
-       return ldb_next_request(ac->module, ac->search_req);
+       return ldb_next_request(module, remote_req);
 }
 
-/* After we find out the objectGUID for the entry, modify the local
- * password database as required */
-static int local_password_mod_local(struct ldb_handle *h) {
+/* On a modify, we don't have the objectGUID handy, so we need to
+ * search our DN for it */
+static int lpdb_delete_callabck(struct ldb_request *req,
+                               struct ldb_reply *ares)
+{
+       static const char * const attrs[] = { "objectGUID", "objectClass", NULL };
+       struct ldb_request *search_req;
+       struct lpdb_context *ac;
+       int ret;
 
+       ac = talloc_get_type(req->context, struct lpdb_context);
+
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
+
+       if (ares->type != LDB_REPLY_DONE) {
+               ldb_set_errstring(ac->module->ldb, "Unexpected reply type");
+               talloc_free(ares);
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+
+       ac->remote_done = talloc_steal(ac, ares);
+
+       /* prepare the search operation */
+       ret = ldb_build_search_req(&search_req, ac->module->ldb, ac,
+                                  ac->req->op.del.dn, LDB_SCOPE_BASE,
+                                  "(objectclass=*)", attrs,
+                                  NULL,
+                                  ac, lpdb_del_search_callback,
+                                  ac->req);
+       if (ret != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+
+       ret = ldb_next_request(ac->module, search_req);
+       if (ret != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       return LDB_SUCCESS;
+}
+
+/* Called when we search for our own entry.  Stores the one entry we
+ * expect (as it is a base search) on the context pointer */
+static int lpdb_del_search_callback(struct ldb_request *req,
+                                   struct ldb_reply *ares)
+{
+       struct ldb_request *local_req;
        struct lpdb_context *ac;
+       struct ldb_dn *local_dn;
        struct GUID objectGUID;
-       ac = talloc_get_type(h->private_data, struct lpdb_context);
-
-       /* if it is not an entry of type person this is an error */
-       /* TODO: remove this when these things are checked in the schema */
-       if (!ac->search_res) {
-               ldb_asprintf_errstring(ac->module->ldb, 
-                                       "entry just modified (%s) not found!",
-                                       ldb_dn_get_linearized(ac->remote_req->op.mod.message->dn));
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-       if (!ldb_msg_check_string_attribute(ac->search_res->message, "objectClass", "person")) {
-               /* Not relevent to us */
-               return LDB_SUCCESS;
+       int ret = LDB_SUCCESS;
+
+       ac = talloc_get_type(req->context, struct lpdb_context);
+
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
        }
-       
-       if (ldb_msg_find_ldb_val(ac->search_res->message, "objectGUID") == NULL) {
-               ldb_set_errstring(ac->module->ldb, 
-                                 "no objectGUID found in search: local_password module must be configured below objectGUID module!\n");
-               return LDB_ERR_OBJECT_CLASS_VIOLATION;
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
        }
-       
-       objectGUID = samdb_result_guid(ac->search_res->message, "objectGUID");
 
-       ac->local_message->dn = ldb_dn_new(ac, ac->module->ldb, LOCAL_BASE);
-       ldb_dn_add_child_fmt(ac->local_message->dn, PASSWORD_GUID_ATTR "=%s", GUID_string(ac, &objectGUID));
+       switch (ares->type) {
+       case LDB_REPLY_ENTRY:
+               if (ac->remote != NULL) {
+                       ldb_set_errstring(ac->module->ldb, "Too many results");
+                       talloc_free(ares);
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
+               }
+
+               ac->remote = talloc_steal(ac, ares);
+               break;
+
+       case LDB_REPLY_REFERRAL:
 
-       h->state = LDB_ASYNC_INIT;
-       h->status = LDB_SUCCESS;
+               /* ignore */
+               talloc_free(ares);
+               break;
 
-       ac->step = LPDB_LOCAL;
+       case LDB_REPLY_DONE:
+               /* After we find out the objectGUID for the entry, modify the local
+                * password database as required */
 
-       ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->local_req);
+               talloc_free(ares);
+
+               /* if it is not an entry of type person this is NOT an error */
+               /* TODO: remove this when sambaPassword will be in schema */
+               if (ac->remote == NULL) {
+                       return ldb_module_done(ac->req,
+                                               ac->remote_done->controls,
+                                               ac->remote_done->response,
+                                               ac->remote_done->error);
+               }
+               if (!ldb_msg_check_string_attribute(ac->remote->message,
+                                                   "objectClass", "person")) {
+                       /* Not relevent to us */
+                       return ldb_module_done(ac->req,
+                                               ac->remote_done->controls,
+                                               ac->remote_done->response,
+                                               ac->remote_done->error);
+               }
+
+               if (ldb_msg_find_ldb_val(ac->remote->message,
+                                        "objectGUID") == NULL) {
+                       ldb_set_errstring(ac->module->ldb,
+                                         "no objectGUID found in search: "
+                                         "local_password module must be "
+                                         "configured below objectGUID "
+                                         "module!\n");
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OBJECT_CLASS_VIOLATION);
+               }
+
+               objectGUID = samdb_result_guid(ac->remote->message,
+                                               "objectGUID");
+
+               local_dn = ldb_dn_new(ac, ac->module->ldb, LOCAL_BASE);
+               if ((local_dn == NULL) ||
+                   ( ! ldb_dn_add_child_fmt(local_dn,
+                                           PASSWORD_GUID_ATTR "=%s",
+                                           GUID_string(ac, &objectGUID)))) {
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
+               }
+
+               ret = ldb_build_del_req(&local_req, ac->module->ldb, ac,
+                                       local_dn,
+                                       NULL,
+                                       ac, lpdb_local_callback,
+                                       ac->req);
+               if (ret != LDB_SUCCESS) {
+                       return ldb_module_done(ac->req, NULL, NULL, ret);
+               }
 
-       /* perform the local update */
-       return ldb_next_request(ac->module, ac->local_req);
+               /* perform the local update */
+               ret = ldb_next_request(ac->module, local_req);
+               if (ret != LDB_SUCCESS) {
+                       return ldb_module_done(ac->req, NULL, NULL, ret);
+               }
+       }
+
+       return LDB_SUCCESS;
 }
 
 
-static int lpdb_local_search_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares)
+/*****************************************************************************
+ * SEARCH
+ ****************************************************************************/
+
+static int lpdb_local_search_callback(struct ldb_request *req,
+                                       struct ldb_reply *ares);
+
+static int lpdb_local_search(struct lpdb_context *ac)
+{
+       struct ldb_request *local_req;
+       int ret;
+
+       ret = ldb_build_search_req(&local_req, ac->module->ldb, ac,
+                                  ac->current->local_dn,
+                                  LDB_SCOPE_BASE,
+                                  "(objectclass=*)",
+                                  ac->req->op.search.attrs,
+                                  NULL,
+                                  ac, lpdb_local_search_callback,
+                                  ac->req);
+       if (ret != LDB_SUCCESS) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       return ldb_next_request(ac->module, local_req);
+}
+
+static int lpdb_local_search_callback(struct ldb_request *req,
+                                       struct ldb_reply *ares)
 {
-       struct lpdb_local_search_context *local_context;
+       struct lpdb_context *ac;
+       struct ldb_reply *merge;
+       struct lpdb_reply *lr;
+       int ret;
+       int i;
+
+       ac = talloc_get_type(req->context, struct lpdb_context);
+
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
 
-       local_context = talloc_get_type(context, struct lpdb_local_search_context);
+       lr = ac->current;
 
-       /* we are interested only in the single reply (base search) we receive here */
+       /* we are interested only in a single reply (base search) */
        switch (ares->type) {
        case LDB_REPLY_ENTRY:
-       {
-               int i;
-               if (local_context->local_res != NULL) {
-                       ldb_set_errstring(ldb, "Too many results to base search for password entry!");
+
+               if (lr->remote == NULL) {
+                       ldb_set_errstring(ac->module->ldb,
+                               "Too many results for password entry search!");
                        talloc_free(ares);
-                       return LDB_ERR_OPERATIONS_ERROR;
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
                }
-               
-               local_context->local_res = ares;
 
-               /* Make sure never to return the internal key attribute to the caller */
+               merge = lr->remote;
+               lr->remote = NULL;
+
+               /* steal the local results on the remote results to be
+                * returned all together */
+               talloc_steal(merge, ares->message->elements);
+
+               /* Make sure never to return the internal key attribute */
                ldb_msg_remove_attr(ares->message, PASSWORD_GUID_ATTR);
 
-               talloc_steal(local_context->remote_res->message->elements, ares->message->elements);
                for (i=0; i < ares->message->num_elements; i++) {
                        struct ldb_message_element *el;
                        
-                       el = ldb_msg_find_element(local_context->remote_res->message, 
+                       el = ldb_msg_find_element(merge->message,
                                                  ares->message->elements[i].name);
                        if (!el) {
-                               if (ldb_msg_add_empty(local_context->remote_res->message, 
-                                                     ares->message->elements[i].name, 0, &el) != LDB_SUCCESS) {
+                               ret = ldb_msg_add_empty(merge->message,
+                                                       ares->message->elements[i].name,
+                                                       0, &el);
+                               if (ret != LDB_SUCCESS) {
                                        talloc_free(ares);
-                                       return LDB_ERR_OPERATIONS_ERROR;
+                                       return ldb_module_done(ac->req,
+                                                               NULL, NULL,
+                                                               LDB_ERR_OPERATIONS_ERROR);
                                }
                                *el = ares->message->elements[i];
                        }
                }
-               return local_context->ac->orig_req->callback(ldb, 
-                                                                  local_context->ac->orig_req->context,
-                                                                  local_context->remote_res);
-       } 
-       case LDB_REPLY_DONE:
-       {
-               /* Fire off the callback if there was no local entry, so we get the rest returned */
-               if (local_context->local_res == NULL) {
-                       return local_context->ac->orig_req->callback(ldb, 
-                                                                          local_context->ac->orig_req->context,
-                                                                          local_context->remote_res);
-               }
-               return LDB_SUCCESS;
+
+               /* free the rest */
+               talloc_free(ares);
+
+               return ldb_module_send_entry(ac->req, merge->message);
+
+       case LDB_REPLY_REFERRAL:
+               /* ignore */
+               talloc_free(ares);
                break;
-       }
-       default:
-       {
+
+       case LDB_REPLY_DONE:
+
                talloc_free(ares);
-               ldb_set_errstring(ldb, "Unexpected result type in base search for password entry!");
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
+
+               /* if this entry was not returned yet, return it now */
+               if (lr->remote) {
+                       ret = ldb_module_send_entry(ac->req, ac->remote->message);
+                       if (ret != LDB_SUCCESS) {
+                               return ldb_module_done(ac->req,
+                                                       NULL, NULL, ret);
+                       }
+                       lr->remote = NULL;
+               }
+
+               if (lr->next->remote->type == LDB_REPLY_DONE) {
+                       /* this was the last one */
+                       return ldb_module_done(ac->req,
+                                               lr->next->remote->controls,
+                                               lr->next->remote->response,
+                                               lr->next->remote->error);
+               } else {
+                       /* next one */
+                       ac->current = lr->next;
+                       talloc_free(lr);
+
+                       ret = lpdb_local_search(ac);
+                       if (ret != LDB_SUCCESS) {
+                               return ldb_module_done(ac->req,
+                                                       NULL, NULL, ret);
+                       }
+               }
        }
+
+       return LDB_SUCCESS;
 }
 
 /* For each entry returned in a remote search, do a local base search,
  * based on the objectGUID we asked for as an additional attribute */
-static int lpdb_remote_search_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares)
+static int lpdb_remote_search_callback(struct ldb_request *req,
+                                       struct ldb_reply *ares)
 {
        struct lpdb_context *ac;
+       struct ldb_dn *local_dn;
+       struct GUID objectGUID;
+       struct lpdb_reply *lr;
+       int ret;
 
-       ac = talloc_get_type(context, struct lpdb_context);
+       ac = talloc_get_type(req->context, struct lpdb_context);
 
-       if (ares->type == LDB_REPLY_ENTRY) {
-               struct ldb_request *req;
-               struct lpdb_local_search_context *local_context;
-               struct GUID objectGUID;
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
 
+       switch (ares->type) {
+       case LDB_REPLY_ENTRY:
                /* No point searching further if it's not a 'person' entry */
                if (!ldb_msg_check_string_attribute(ares->message, "objectClass", "person")) {
 
@@ -538,13 +898,14 @@ static int lpdb_remote_search_callback(struct ldb_context *ldb, void *context, s
                                ldb_msg_remove_attr(ares->message, "objectClass");
                        }
                        
-                       return ac->orig_req->callback(ldb, ac->orig_req->context, ares);
+                       return ldb_module_send_entry(ac->req, ares->message);
                }
 
                if (ldb_msg_find_ldb_val(ares->message, "objectGUID") == NULL) {
                        ldb_set_errstring(ac->module->ldb, 
                                          "no objectGUID found in search: local_password module must be configured below objectGUID module!\n");
-                       return LDB_ERR_OPERATIONS_ERROR;
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
                }
        
                objectGUID = samdb_result_guid(ares->message, "objectGUID");
@@ -557,44 +918,63 @@ static int lpdb_remote_search_callback(struct ldb_context *ldb, void *context, s
                        ldb_msg_remove_attr(ares->message, "objectClass");
                }
 
-               req = talloc_zero(ac, struct ldb_request);
-               if (!req) {
-                       return LDB_ERR_OPERATIONS_ERROR;
+               local_dn = ldb_dn_new(ac, ac->module->ldb, LOCAL_BASE);
+               if ((local_dn == NULL) ||
+                   (! ldb_dn_add_child_fmt(local_dn,
+                                           PASSWORD_GUID_ATTR "=%s",
+                                           GUID_string(ac, &objectGUID)))) {
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
+               }
+
+               lr = talloc_zero(ac, struct lpdb_reply);
+               if (lr == NULL) {
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
                }
+               lr->local_dn = talloc_steal(lr, local_dn);
+               lr->remote = talloc_steal(lr, ares);
 
-               local_context = talloc(ac, struct lpdb_local_search_context);
-               if (!local_context) {
-                       return LDB_ERR_OPERATIONS_ERROR;
+               if (ac->list) {
+                       ac->current->next = lr;
+               } else {
+                       ac->list = lr;
                }
-               local_context->ac = ac;
-               local_context->remote_res = ares;
-               local_context->local_res = NULL;
+               ac->current= lr;
+
+               break;
 
-               req->op.search.base = ldb_dn_new(ac, ac->module->ldb, LOCAL_BASE);
-               if ( ! ldb_dn_add_child_fmt(req->op.search.base, PASSWORD_GUID_ATTR "=%s", GUID_string(ac, &objectGUID))) {
-                       return LDB_ERR_OPERATIONS_ERROR;
+       case LDB_REPLY_REFERRAL:
+
+               return ldb_module_send_referral(ac->req, ares->referral);
+
+       case LDB_REPLY_DONE:
+
+               if (ac->list == NULL) {
+                       /* found nothing */
+                       return ldb_module_done(ac->req, ares->controls,
+                                               ares->response, ares->error);
                }
-               req->operation = LDB_SEARCH;
-               req->op.search.scope = LDB_SCOPE_BASE;
-               req->op.search.tree = ldb_parse_tree(req, NULL);
-               if (req->op.search.tree == NULL) {
-                       ldb_set_errstring(ac->module->ldb, "Out of Memory");
-                       return LDB_ERR_OPERATIONS_ERROR;
+
+               lr = talloc_zero(ac, struct lpdb_reply);
+               if (lr == NULL) {
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
                }
-               req->op.search.attrs = ac->orig_req->op.search.attrs;
-               req->controls = NULL;
-               req->context = ac;
-               req->callback = get_self_callback;
+               lr->remote = talloc_steal(lr, ares);
 
-               ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, req);
-               
-               req->context = local_context;
-               req->callback = lpdb_local_search_callback;
+               ac->current->next = lr;
 
-               return ldb_next_request(ac->module, req);
-       } else {
-               return ac->orig_req->callback(ldb, ac->orig_req->context, ares);
+               /* rewind current and start local searches */
+               ac->current= ac->list;
+
+               ret = lpdb_local_search(ac);
+               if (ret != LDB_SUCCESS) {
+                       return ldb_module_done(ac->req, NULL, NULL, ret);
+               }
        }
+
+       return LDB_SUCCESS;
 }
 
 /* Search for passwords and other attributes.  The passwords are
@@ -603,7 +983,7 @@ static int lpdb_remote_search_callback(struct ldb_context *ldb, void *context, s
 
 static int local_password_search(struct ldb_module *module, struct ldb_request *req)
 {
-       struct ldb_handle *h;
+       struct ldb_request *remote_req;
        struct lpdb_context *ac;
        int i;
        int ret;
@@ -615,6 +995,8 @@ static int local_password_search(struct ldb_module *module, struct ldb_request *
                return ldb_next_request(module, req);
        }
 
+       search_attrs = NULL;
+
        /* If the caller is searching for the local passwords directly, let them pass */
        if (ldb_dn_compare_base(ldb_dn_new(req, module->ldb, LOCAL_BASE),
                                req->op.search.base) == 0) {
@@ -634,32 +1016,15 @@ static int local_password_search(struct ldb_module *module, struct ldb_request *
                }
        }
 
-       h = lpdb_init_handle(req, module, LPDB_SEARCH);
-       if (!h) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-       
-       ac = talloc_get_type(h->private_data, struct lpdb_context);
-
-       ac->orig_req = req;
-
-       ac->remote_req = talloc(ac, struct ldb_request);
-       if (ac->remote_req == NULL) {
+       ac = lpdb_init_context(module, req);
+       if (!ac) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
        /* Remote search is for all attributes: if the remote LDAP server has these attributes, then it overrides the local database */
-       *(ac->remote_req) = *(ac->orig_req);
-
-       /* Return our own handle do deal with this call */
-       ac->remote_req->handle = h;
-       
-       ac->remote_req->context = ac;
-       ac->remote_req->callback = lpdb_remote_search_callback;
-
        if (req->op.search.attrs && !ldb_attr_in_list(req->op.search.attrs, "*")) {
                if (!ldb_attr_in_list(req->op.search.attrs, "objectGUID")) {
-                       search_attrs = ldb_attr_list_copy_add(req, req->op.search.attrs, "objectGUID");
+                       search_attrs = ldb_attr_list_copy_add(ac, req->op.search.attrs, "objectGUID");
                        ac->added_objectGUID = true;
                        if (!search_attrs) {
                                return LDB_ERR_OPERATIONS_ERROR;
@@ -668,7 +1033,7 @@ static int local_password_search(struct ldb_module *module, struct ldb_request *
                        search_attrs = req->op.search.attrs;
                }
                if (!ldb_attr_in_list(search_attrs, "objectClass")) {
-                       search_attrs = ldb_attr_list_copy_add(req, search_attrs, "objectClass");
+                       search_attrs = ldb_attr_list_copy_add(ac, search_attrs, "objectClass");
                        ac->added_objectClass = true;
                        if (!search_attrs) {
                                return LDB_ERR_OPERATIONS_ERROR;
@@ -678,175 +1043,26 @@ static int local_password_search(struct ldb_module *module, struct ldb_request *
                search_attrs = req->op.search.attrs;
        }
 
-       ac->remote_req->op.search.attrs = search_attrs;
-
-       ldb_set_timeout_from_prev_req(module->ldb, ac->orig_req, ac->remote_req);
-
-       h->state = LDB_ASYNC_INIT;
-       h->status = LDB_SUCCESS;
-
-       ac->step = LPDB_SEARCH_REMOTE;
-
-       /* perform the search */
-       ret = ldb_next_request(module, ac->remote_req);
-
-       if (ret == LDB_SUCCESS) {
-               req->handle = ac->remote_req->handle;
-       }
-
-       return ret;
-}
-
-static int lpdb_wait(struct ldb_handle *handle) {
-       struct lpdb_context *ac;
-       int ret;
-    
-       if (!handle || !handle->private_data) {
+       ret = ldb_build_search_req_ex(&remote_req, module->ldb, ac,
+                                       req->op.search.base,
+                                       req->op.search.scope,
+                                       req->op.search.tree,
+                                       search_attrs,
+                                       req->controls,
+                                       ac, lpdb_remote_search_callback,
+                                       req);
+       if (ret != LDB_SUCCESS) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       if (handle->state == LDB_ASYNC_DONE) {
-               return handle->status;
-       }
-
-       handle->state = LDB_ASYNC_PENDING;
-       handle->status = LDB_SUCCESS;
-
-       ac = talloc_get_type(handle->private_data, struct lpdb_context);
-
-       switch (ac->step) {
-       case LPDB_ADD_REMOTE:
-               ret = ldb_wait(ac->remote_req->handle, LDB_WAIT_NONE);
-
-               if (ret != LDB_SUCCESS) {
-                       handle->status = ret;
-                       goto done;
-               }
-               if (ac->remote_req->handle->status != LDB_SUCCESS) {
-                       handle->status = ac->remote_req->handle->status;
-                       goto done;
-               }
-
-               if (ac->remote_req->handle->state != LDB_ASYNC_DONE) {
-                       return LDB_SUCCESS;
-               }
-
-               /* original request done, go on */
-               return local_password_add_local(handle);
-               
-       case LPDB_MOD_REMOTE:
-               ret = ldb_wait(ac->remote_req->handle, LDB_WAIT_NONE);
-
-               if (ret != LDB_SUCCESS) {
-                       handle->status = ret;
-                       goto done;
-               }
-               if (ac->remote_req->handle->status != LDB_SUCCESS) {
-                       handle->status = ac->remote_req->handle->status;
-                       goto done;
-               }
-
-               if (ac->remote_req->handle->state != LDB_ASYNC_DONE) {
-                       return LDB_SUCCESS;
-               }
-
-               /* original request done, go on */
-               return local_password_mod_search_self(handle);
-               
-       case LPDB_MOD_SEARCH_SELF:
-               ret = ldb_wait(ac->search_req->handle, LDB_WAIT_NONE);
-
-               if (ret != LDB_SUCCESS) {
-                       handle->status = ret;
-                       goto done;
-               }
-               if (ac->search_req->handle->status != LDB_SUCCESS) {
-                       handle->status = ac->search_req->handle->status;
-                       goto done;
-               }
-
-               if (ac->search_req->handle->state != LDB_ASYNC_DONE) {
-                       return LDB_SUCCESS;
-               }
-
-               /* original request done, go on */
-               return local_password_mod_local(handle);
-               
-       case LPDB_LOCAL:
-               ret = ldb_wait(ac->local_req->handle, LDB_WAIT_NONE);
-
-               if (ret != LDB_SUCCESS) {
-                       handle->status = ret;
-                       goto done;
-               }
-               if (ac->local_req->handle->status != LDB_SUCCESS) {
-                       handle->status = ac->local_req->handle->status;
-                       goto done;
-               }
-
-               if (ac->local_req->handle->state != LDB_ASYNC_DONE) {
-                       return LDB_SUCCESS;
-               }
-
-               break;
-               
-       case LPDB_SEARCH_REMOTE:
-               ret = ldb_wait(ac->remote_req->handle, LDB_WAIT_NONE);
-
-               if (ret != LDB_SUCCESS) {
-                       handle->status = ret;
-                       goto done;
-               }
-               if (ac->remote_req->handle->status != LDB_SUCCESS) {
-                       handle->status = ac->remote_req->handle->status;
-                       goto done;
-               }
-
-               if (ac->remote_req->handle->state != LDB_ASYNC_DONE) {
-                       return LDB_SUCCESS;
-               }
-
-               break;
-               
-       default:
-               ret = LDB_ERR_OPERATIONS_ERROR;
-               goto done;
-       }
-
-       ret = LDB_SUCCESS;
-
-done:
-       handle->state = LDB_ASYNC_DONE;
-       return ret;
-}
-
-static int lpdb_wait_all(struct ldb_handle *handle) {
-
-       int ret;
-
-       while (handle->state != LDB_ASYNC_DONE) {
-               ret = lpdb_wait(handle);
-               if (ret != LDB_SUCCESS) {
-                       return ret;
-               }
-       }
-
-       return handle->status;
-}
-
-static int local_password_wait(struct ldb_handle *handle, enum ldb_wait_type type)
-{
-       if (type == LDB_WAIT_ALL) {
-               return lpdb_wait_all(handle);
-       } else {
-               return lpdb_wait(handle);
-       }
+       /* perform the search */
+       return ldb_next_request(module, remote_req);
 }
 
 _PUBLIC_ const struct ldb_module_ops ldb_local_password_module_ops = {
        .name          = "local_password",
        .add           = local_password_add,
        .modify        = local_password_modify,
-       .search        = local_password_search,
-       .wait          = local_password_wait
+       .del           = local_password_delete,
+       .search        = local_password_search
 };
index 3306fd3c33b9f8cba6b1bd76d674465c3160d83c..70513bd644cc189f554c8c893e9fce90f99e96bf 100644 (file)
     CN=Admins,CN=Users,DC=samba,DC=example,DC=com
    
  */
+
+struct norm_context {
+       struct ldb_module *module;
+       struct ldb_request *req;
+
+       const struct dsdb_schema *schema;
+};
+
 static int fix_dn(struct ldb_dn *dn) 
 {
        int i, ret;
@@ -69,93 +77,117 @@ static int fix_dn(struct ldb_dn *dn)
        return LDB_SUCCESS;
 }
 
-static int normalise_search_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares) 
+static int normalize_search_callback(struct ldb_request *req, struct ldb_reply *ares)
 {
-       const struct dsdb_schema *schema = dsdb_get_schema(ldb);
-       struct ldb_request *orig_req = talloc_get_type(context, struct ldb_request);
-       TALLOC_CTX *mem_ctx;
+       struct ldb_message *msg;
+       struct norm_context *ac;
        int i, j, ret;
 
-       /* Only entries are interesting, and we handle the case of the parent seperatly */
-       if (ares->type != LDB_REPLY_ENTRY) {
-               return orig_req->callback(ldb, orig_req->context, ares);
-       }
+       ac = talloc_get_type(req->context, struct norm_context);
 
-       if (!schema) {
-               return orig_req->callback(ldb, orig_req->context, ares);
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
        }
-
-       mem_ctx = talloc_new(ares);
-       if (!mem_ctx) {
-               ldb_oom(ldb);
-               return LDB_ERR_OPERATIONS_ERROR;
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
        }
 
-       /* OK, we have one of *many* search results passing by here,
-        * but we should get them one at a time */
+       /* Only entries are interesting, and we handle the case of the parent seperatly */
 
-       ret = fix_dn(ares->message->dn);
-       if (ret != LDB_SUCCESS) {
-               talloc_free(mem_ctx);
-               return ret;
-       }
+       switch (ares->type) {
+       case LDB_REPLY_ENTRY:
 
-       for (i = 0; i < ares->message->num_elements; i++) {
-               const struct dsdb_attribute *attribute = dsdb_attribute_by_lDAPDisplayName(schema, ares->message->elements[i].name);
-               if (!attribute) {
-                       continue;
-               }
-               /* Look to see if this attributeSyntax is a DN */
-               if (!((strcmp(attribute->attributeSyntax_oid, "2.5.5.1") == 0) ||
-                     (strcmp(attribute->attributeSyntax_oid, "2.5.5.7") == 0))) {
-                       continue;
+               /* OK, we have one of *many* search results passing by here,
+                * but we should get them one at a time */
+               msg = ares->message;
+
+               ret = fix_dn(msg->dn);
+               if (ret != LDB_SUCCESS) {
+                       return ldb_module_done(ac->req, NULL, NULL, ret);
                }
-               for (j = 0; j < ares->message->elements[i].num_values; j++) {
-                       const char *dn_str;
-                       struct ldb_dn *dn = ldb_dn_from_ldb_val(mem_ctx, ldb, &ares->message->elements[i].values[j]);
-                       if (!dn) {
-                               talloc_free(mem_ctx);
-                               return LDB_ERR_OPERATIONS_ERROR;
+
+               for (i = 0; i < msg->num_elements; i++) {
+                       const struct dsdb_attribute *attribute = dsdb_attribute_by_lDAPDisplayName(ac->schema, msg->elements[i].name);
+                       if (!attribute) {
+                               continue;
                        }
-                       ret = fix_dn(dn);
-                       if (ret != LDB_SUCCESS) {
-                               talloc_free(mem_ctx);
-                               return ret;
+                       /* Look to see if this attributeSyntax is a DN */
+                       if (!((strcmp(attribute->attributeSyntax_oid, "2.5.5.1") == 0) ||
+                             (strcmp(attribute->attributeSyntax_oid, "2.5.5.7") == 0))) {
+                               continue;
+                       }
+                       for (j = 0; j < msg->elements[i].num_values; j++) {
+                               const char *dn_str;
+                               struct ldb_dn *dn = ldb_dn_new(ac, ac->module->ldb, (const char *)msg->elements[i].values[j].data);
+                               if (!dn) {
+                                       return ldb_module_done(ac->req, NULL, NULL, LDB_ERR_OPERATIONS_ERROR);
+                               }
+                               ret = fix_dn(dn);
+                               if (ret != LDB_SUCCESS) {
+                                       return ldb_module_done(ac->req, NULL, NULL, ret);
+                               }
+                               dn_str = talloc_steal(msg->elements[i].values, ldb_dn_get_linearized(dn));
+                               msg->elements[i].values[j] = data_blob_string_const(dn_str);
+                               talloc_free(dn);
                        }
-                       dn_str = talloc_steal(ares->message->elements[i].values, ldb_dn_get_linearized(dn));
-                       ares->message->elements[i].values[j] = data_blob_string_const(dn_str);
-                       talloc_free(dn);
                }
+
+               return ldb_module_send_entry(ac->req, msg);
+
+       case LDB_REPLY_REFERRAL:
+
+               return ldb_module_send_referral(ac->req, ares->referral);
+
+       case LDB_REPLY_DONE:
+
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
        }
-       talloc_free(mem_ctx);
-       return orig_req->callback(ldb, orig_req->context, ares);
+
+       return LDB_SUCCESS;
 }
 
 /* search */
 static int normalise_search(struct ldb_module *module, struct ldb_request *req)
 {
+       struct ldb_request *down_req;
+       struct norm_context *ac;
        int ret;
-       struct ldb_request *down_req = talloc(req, struct ldb_request);
-       if (!down_req) {
-               ldb_oom(module->ldb);
+
+       ac = talloc(req, struct norm_context);
+       if (ac == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       
-       *down_req = *req;
-       down_req->context = req;
-       down_req->callback = normalise_search_callback;
 
-       ret = ldb_next_request(module, down_req);
+       ac->module = module;
+       ac->req = req;
 
-       /* do not free down_req as the call results may be linked to it,
-        * it will be freed when the upper level request get freed */
-       if (ret == LDB_SUCCESS) {
-               req->handle = down_req->handle;
+       /* if schema not yet present just skip over */
+       ac->schema = dsdb_get_schema(ac->module->ldb);
+       if (ac->schema == NULL) {
+               talloc_free(ac);
+               return ldb_next_request(module, req);
        }
-       return ret;
+
+       ret = ldb_build_search_req_ex(&down_req, module->ldb, ac,
+                                       req->op.search.base,
+                                       req->op.search.scope,
+                                       req->op.search.tree,
+                                       req->op.search.attrs,
+                                       req->controls,
+                                       ac, normalize_search_callback,
+                                       req);
+       if (ret != LDB_SUCCESS) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       return ldb_next_request(module, down_req);
 }
 
 
+
 _PUBLIC_ const struct ldb_module_ops ldb_normalise_module_ops = {
        .name              = "normalise",
        .search            = normalise_search,
index b048a8d8e1e2aa06a7fa05101f5db4fdea9cc84c..2c242d47c68e6db5e5468f9bc9f212aea11a2bff 100644 (file)
@@ -1,7 +1,7 @@
 /* 
    ldb database library
 
-   Copyright (C) Simo Sorce  2006
+   Copyright (C) Simo Sorce  2006-2008
    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005-2007
 
    This program is free software; you can redistribute it and/or modify
 
 struct oc_context {
 
-       enum oc_step {OC_DO_REQ, OC_SEARCH_SELF, OC_DO_MOD, 
-                     OC_SEARCH_ADD_PARENT, OC_DO_ADD, 
-                     OC_SEARCH_RENAME_PARENT, OC_DO_RENAME} step;
-
        struct ldb_module *module;
-       struct ldb_request *orig_req;
-
-       struct ldb_request *down_req;
+       struct ldb_request *req;
 
-       struct ldb_request *search_req;
        struct ldb_reply *search_res;
 
-       struct ldb_request *add_req;
-       struct ldb_request *mod_req;
-       struct ldb_request *rename_req;
+       int (*step_fn)(struct oc_context *);
 };
 
 struct class_list {
@@ -69,46 +60,31 @@ struct class_list {
        const struct dsdb_class *objectclass;
 };
 
-static int objectclass_do_add(struct ldb_handle *h);
-
-static struct ldb_handle *oc_init_handle(struct ldb_request *req, struct ldb_module *module)
+static struct oc_context *oc_init_context(struct ldb_module *module,
+                                         struct ldb_request *req)
 {
        struct oc_context *ac;
-       struct ldb_handle *h;
 
-       h = talloc_zero(req, struct ldb_handle);
-       if (h == NULL) {
-               ldb_set_errstring(module->ldb, "Out of Memory");
-               return NULL;
-       }
-
-       h->module = module;
-
-       ac = talloc_zero(h, struct oc_context);
+       ac = talloc_zero(req, struct oc_context);
        if (ac == NULL) {
                ldb_set_errstring(module->ldb, "Out of Memory");
-               talloc_free(h);
                return NULL;
        }
 
-       h->private_data = (void *)ac;
-
-       h->state = LDB_ASYNC_INIT;
-       h->status = LDB_SUCCESS;
-
        ac->module = module;
-       ac->orig_req = req;
+       ac->req = req;
 
-       return h;
+       return ac;
 }
 
+static int objectclass_do_add(struct oc_context *ac);
+
 /* Sort objectClasses into correct order, and validate that all
  * objectClasses specified actually exist in the schema
  */
 
 static int objectclass_sort(struct ldb_module *module,
                            const struct dsdb_schema *schema,
-                           struct ldb_message *msg, /* so that when we create new elements, we put it on the right parent */
                            TALLOC_CTX *mem_ctx,
                            struct ldb_message_element *objectclass_element,
                            struct class_list **sorted_out) 
@@ -117,6 +93,7 @@ static int objectclass_sort(struct ldb_module *module,
        int layer;
        struct class_list *sorted = NULL, *parent_class = NULL,
                *subclass = NULL, *unsorted = NULL, *current, *poss_subclass, *poss_parent, *new_parent;
+
        /* DESIGN:
         *
         * We work on 4 different 'bins' (implemented here as linked lists):
@@ -150,8 +127,7 @@ static int objectclass_sort(struct ldb_module *module,
        for (i=0; i < objectclass_element->num_values; i++) {
                current = talloc(mem_ctx, struct class_list);
                if (!current) {
-                       ldb_set_errstring(module->ldb, "objectclass: out of memory allocating objectclass list");
-                       talloc_free(mem_ctx);
+                       ldb_oom(module->ldb);
                        return LDB_ERR_OPERATIONS_ERROR;
                }
                current->objectclass = dsdb_class_by_lDAPDisplayName(schema, (const char *)objectclass_element->values[i].data);
@@ -258,7 +234,7 @@ static DATA_BLOB *get_sd(struct ldb_module *module, TALLOC_CTX *mem_ctx,
        struct auth_session_info *session_info
                = ldb_get_opaque(module->ldb, "sessionInfo");
        struct security_descriptor *sd;
-       struct dom_sid *domain_sid = samdb_domain_sid(module->ldb);
+       const struct dom_sid *domain_sid = samdb_domain_sid(module->ldb);
 
        if (!objectclass->defaultSecurityDescriptor || !domain_sid) {
                return NULL;
@@ -292,28 +268,77 @@ static DATA_BLOB *get_sd(struct ldb_module *module, TALLOC_CTX *mem_ctx,
 
 }
 
-static int get_search_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares)
+static int get_search_callback(struct ldb_request *req, struct ldb_reply *ares)
 {
        struct oc_context *ac;
+       int ret;
 
-       ac = talloc_get_type(context, struct oc_context);
+       ac = talloc_get_type(req->context, struct oc_context);
 
-       /* we are interested only in the single reply (base search) we receive here */
-       if (ares->type == LDB_REPLY_ENTRY) {
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS &&
+           ares->error != LDB_ERR_NO_SUCH_OBJECT) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
+
+       switch (ares->type) {
+       case LDB_REPLY_ENTRY:
                if (ac->search_res != NULL) {
-                       ldb_set_errstring(ldb, "Too many results");
+                       ldb_set_errstring(ac->module->ldb, "Too many results");
                        talloc_free(ares);
-                       return LDB_ERR_OPERATIONS_ERROR;
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
                }
 
-               ac->search_res = talloc_move(ac, &ares);
-       } else {
+               ac->search_res = talloc_steal(ac, ares);
+               break;
+
+       case LDB_REPLY_REFERRAL:
+               /* ignore */
+               talloc_free(ares);
+               break;
+
+       case LDB_REPLY_DONE:
                talloc_free(ares);
+               ret = ac->step_fn(ac);
+               if (ret != LDB_SUCCESS) {
+                       return ldb_module_done(ac->req, NULL, NULL, ret);
+               }
+               break;
        }
 
        return LDB_SUCCESS;
 }
 
+static int oc_op_callback(struct ldb_request *req, struct ldb_reply *ares)
+{
+       struct oc_context *ac;
+
+       ac = talloc_get_type(req->context, struct oc_context);
+
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
+
+       if (ares->type != LDB_REPLY_DONE) {
+               talloc_free(ares);
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+
+       return ldb_module_done(ac->req, ares->controls,
+                               ares->response, ares->error);
+}
+
 /* Fix up the DN to be in the standard form, taking particular care to match the parent DN
 
    This should mean that if the parent is:
@@ -367,12 +392,11 @@ static int fix_attributes(struct ldb_context *ldb, const struct dsdb_schema *sch
        return LDB_SUCCESS;
 }
 
+static int objectclass_do_add(struct oc_context *ac);
+
 static int objectclass_add(struct ldb_module *module, struct ldb_request *req)
 {
-
-       static const char * const attrs[] = { NULL };
-
-       struct ldb_handle *h;
+       struct ldb_request *search_req;
        struct oc_context *ac;
        struct ldb_dn *parent_dn;
        int ret;
@@ -384,61 +408,56 @@ static int objectclass_add(struct ldb_module *module, struct ldb_request *req)
                return ldb_next_request(module, req);
        }
 
-       /* Need to object to this, but cn=rootdse doesn't hae an objectClass... */
+       /* Need to object to this, but cn=rootdse doesn't have an objectClass... */
        if (ldb_msg_find_element(req->op.add.message, 
                                 "objectClass") == NULL) {
                return ldb_next_request(module, req);
        }
 
-       h = oc_init_handle(req, module);
-       if (!h) {
+       ac = oc_init_context(module, req);
+       if (ac == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       ac = talloc_get_type(h->private_data, struct oc_context);
-       
-       /* return or own handle to deal with this call */
-       req->handle = h;
 
        /* If there isn't a parent, just go on to the add processing */
-       if (ldb_dn_get_comp_num(ac->orig_req->op.add.message->dn) == 1) {
-               return objectclass_do_add(h);
+       if (ldb_dn_get_comp_num(ac->req->op.add.message->dn) == 1) {
+               return objectclass_do_add(ac);
        }
 
-       parent_dn = ldb_dn_get_parent(ac, ac->orig_req->op.add.message->dn);
+       /* get copy of parent DN */
+       parent_dn = ldb_dn_get_parent(ac, ac->req->op.add.message->dn);
        if (parent_dn == NULL) {
                ldb_oom(module->ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       ret = ldb_build_search_req(&ac->search_req, module->ldb,
+       ret = ldb_build_search_req(&search_req, module->ldb,
                                   ac, parent_dn, LDB_SCOPE_BASE,
-                                  "(objectClass=*)",
-                                  attrs, NULL, 
-                                  ac, get_search_callback);
+                                  "(objectClass=*)", NULL,
+                                  NULL,
+                                  ac, get_search_callback,
+                                  req);
        if (ret != LDB_SUCCESS) {
                return ret;
        }
+       talloc_steal(search_req, parent_dn);
 
-       talloc_steal(ac->search_req, parent_dn);
-
-       ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->search_req);
+       ac->step_fn = objectclass_do_add;
 
-       ac->step = OC_SEARCH_ADD_PARENT;
-
-       return ldb_next_request(ac->module, ac->search_req);
+       return ldb_next_request(ac->module, search_req);
 }
 
-static int objectclass_do_add(struct ldb_handle *h) 
+static int objectclass_do_add(struct oc_context *ac)
 {
        const struct dsdb_schema *schema;
-       struct oc_context *ac;
+       struct ldb_request *add_req;
+       char *value;
        struct ldb_message_element *objectclass_element;
        struct ldb_message *msg;
        TALLOC_CTX *mem_ctx;
        struct class_list *sorted, *current;
        int ret;
-      
-       ac = talloc_get_type(h->private_data, struct oc_context);
+
        schema = dsdb_get_schema(ac->module->ldb);
 
        mem_ctx = talloc_new(ac);
@@ -446,41 +465,34 @@ static int objectclass_do_add(struct ldb_handle *h)
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       ac->add_req = talloc(ac, struct ldb_request);
-       if (ac->add_req == NULL) {
-               talloc_free(mem_ctx);
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
+       msg = ldb_msg_copy_shallow(ac, ac->req->op.add.message);
 
-       *ac->add_req = *ac->orig_req;
-
-       ac->add_req->op.add.message = msg = ldb_msg_copy_shallow(ac->add_req, ac->orig_req->op.add.message);
-
-       ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->add_req);
-       
        /* Check we have a valid parent */
        if (ac->search_res == NULL) {
-               if (ldb_dn_compare(ldb_get_root_basedn(ac->module->ldb), ac->orig_req->op.add.message->dn) == 0) {
+               if (ldb_dn_compare(ldb_get_root_basedn(ac->module->ldb),
+                                                               msg->dn) == 0) {
                        /* Allow the tree to be started */
                        
                        /* but don't keep any error string, it's meaningless */
                        ldb_set_errstring(ac->module->ldb, NULL);
                } else {
                        ldb_asprintf_errstring(ac->module->ldb, "objectclass: Cannot add %s, parent does not exist!", 
-                                              ldb_dn_get_linearized(ac->orig_req->op.add.message->dn));
+                                              ldb_dn_get_linearized(msg->dn));
+                       talloc_free(mem_ctx);
                        return LDB_ERR_UNWILLING_TO_PERFORM;
                }
        } else {
                
                /* Fix up the DN to be in the standard form, taking particular care to match the parent DN */
                ret = fix_dn(msg, 
-                            ac->orig_req->op.add.message->dn,
+                            ac->req->op.add.message->dn,
                             ac->search_res->message->dn,
                             &msg->dn);
 
                if (ret != LDB_SUCCESS) {
                        ldb_asprintf_errstring(ac->module->ldb, "Could not munge DN %s into normal form", 
-                                              ldb_dn_get_linearized(ac->orig_req->op.add.message->dn));
+                                              ldb_dn_get_linearized(ac->req->op.add.message->dn));
+                       talloc_free(mem_ctx);
                        return ret;
                }
 
@@ -505,7 +517,7 @@ static int objectclass_do_add(struct ldb_handle *h)
                        talloc_free(mem_ctx);
                        return LDB_ERR_OPERATIONS_ERROR;
                }
-               ret = objectclass_sort(ac->module, schema, msg, mem_ctx, objectclass_element, &sorted);
+               ret = objectclass_sort(ac->module, schema, mem_ctx, objectclass_element, &sorted);
                if (ret != LDB_SUCCESS) {
                        talloc_free(mem_ctx);
                        return ret;
@@ -524,7 +536,13 @@ static int objectclass_do_add(struct ldb_handle *h)
                
                /* Move from the linked list back into an ldb msg */
                for (current = sorted; current; current = current->next) {
-                       ret = ldb_msg_add_string(msg, "objectClass", current->objectclass->lDAPDisplayName);
+                       value = talloc_strdup(msg, current->objectclass->lDAPDisplayName);
+                       if (value == NULL) {
+                               ldb_oom(ac->module->ldb);
+                               talloc_free(mem_ctx);
+                               return LDB_ERR_OPERATIONS_ERROR;
+                       }
+                       ret = ldb_msg_add_string(msg, "objectClass", value);
                        if (ret != LDB_SUCCESS) {
                                ldb_set_errstring(ac->module->ldb, 
                                                  "objectclass: could not re-add sorted "
@@ -537,8 +555,13 @@ static int objectclass_do_add(struct ldb_handle *h)
                                struct ldb_message_element *el;
                                int32_t systemFlags = 0;
                                if (!ldb_msg_find_element(msg, "objectCategory")) {
-                                       ldb_msg_add_string(msg, "objectCategory", 
-                                                          current->objectclass->defaultObjectCategory);
+                                       value = talloc_strdup(msg, current->objectclass->defaultObjectCategory);
+                                       if (value == NULL) {
+                                               ldb_oom(ac->module->ldb);
+                                               talloc_free(mem_ctx);
+                                               return LDB_ERR_OPERATIONS_ERROR;
+                                       }
+                                       ldb_msg_add_string(msg, "objectCategory", value);
                                }
                                if (!ldb_msg_find_element(msg, "showInAdvancedViewOnly") && (current->objectclass->defaultHidingValue == true)) {
                                        ldb_msg_add_string(msg, "showInAdvancedViewOnly", 
@@ -597,20 +620,33 @@ static int objectclass_do_add(struct ldb_handle *h)
                return ret;
        }
 
-       h->state = LDB_ASYNC_INIT;
-       h->status = LDB_SUCCESS;
-
-       ac->step = OC_DO_ADD;
+       ret = ldb_build_add_req(&add_req, ac->module->ldb, ac,
+                               msg,
+                               ac->req->controls,
+                               ac, oc_op_callback,
+                               ac->req);
+       if (ret != LDB_SUCCESS) {
+               return ret;
+       }
 
        /* perform the add */
-       return ldb_next_request(ac->module, ac->add_req);
+       return ldb_next_request(ac->module, add_req);
 }
 
+static int oc_modify_callback(struct ldb_request *req,
+                               struct ldb_reply *ares);
+static int objectclass_do_mod(struct oc_context *ac);
+
 static int objectclass_modify(struct ldb_module *module, struct ldb_request *req)
 {
        struct ldb_message_element *objectclass_element;
        struct ldb_message *msg;
        const struct dsdb_schema *schema = dsdb_get_schema(module->ldb);
+       struct class_list *sorted, *current;
+       struct ldb_request *down_req;
+       struct oc_context *ac;
+       TALLOC_CTX *mem_ctx;
+       char *value;
        int ret;
 
        ldb_debug(module->ldb, LDB_DEBUG_TRACE, "objectclass_modify\n");
@@ -626,23 +662,19 @@ static int objectclass_modify(struct ldb_module *module, struct ldb_request *req
        }
        objectclass_element = ldb_msg_find_element(req->op.mod.message, "objectClass");
 
+       ac = oc_init_context(module, req);
+       if (ac == NULL) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
        /* If no part of this touches the objectClass, then we don't
         * need to make any changes.  */
 
        /* If the only operation is the deletion of the objectClass
         * then go on with just fixing the attribute case */
        if (!objectclass_element) {
-               struct ldb_request *down_req = talloc(req, struct ldb_request);
-               if (down_req == NULL) {
-                       ldb_set_errstring(module->ldb, "Out of memory!");
-                       return LDB_ERR_OPERATIONS_ERROR;
-               }
-               
-               *down_req = *req; /* copy the request */
-               
-               down_req->op.mod.message = msg = ldb_msg_copy_shallow(down_req, req->op.mod.message);
-               
-               if (down_req->op.mod.message == NULL) {
+               msg = ldb_msg_copy_shallow(ac, req->op.mod.message);
+               if (msg == NULL) {
                        return LDB_ERR_OPERATIONS_ERROR;
                }
                
@@ -651,15 +683,17 @@ static int objectclass_modify(struct ldb_module *module, struct ldb_request *req
                        return ret;
                }
 
-               /* go on with the call chain */
-               ret = ldb_next_request(module, down_req);
-               
-               /* do not free down_req as the call results may be linked to it,
-                * it will be freed when the upper level request get freed */
-               if (ret == LDB_SUCCESS) {
-                       req->handle = down_req->handle;
+               ret = ldb_build_mod_req(&down_req, module->ldb, ac,
+                                       msg,
+                                       req->controls,
+                                       ac, oc_op_callback,
+                                       req);
+               if (ret != LDB_SUCCESS) {
+                       return ret;
                }
-               return ret;
+
+               /* go on with the call chain */
+               return ldb_next_request(module, down_req);
        }
 
        switch (objectclass_element->flags & LDB_FLAG_MOD_MASK) {
@@ -668,41 +702,28 @@ static int objectclass_modify(struct ldb_module *module, struct ldb_request *req
                        return LDB_ERR_OBJECT_CLASS_MODS_PROHIBITED;
                }
                break;
+
        case LDB_FLAG_MOD_REPLACE:
-       {
-               struct ldb_request *down_req;
-               struct class_list *sorted, *current;
-               TALLOC_CTX *mem_ctx;
-               mem_ctx = talloc_new(req);
+               mem_ctx = talloc_new(ac);
                if (mem_ctx == NULL) {
                        return LDB_ERR_OPERATIONS_ERROR;
                }
 
-               /* prepare the first operation */
-               down_req = talloc(req, struct ldb_request);
-               if (down_req == NULL) {
-                       ldb_set_errstring(module->ldb, "Out of memory!");
+               msg = ldb_msg_copy_shallow(ac, req->op.mod.message);
+               if (msg == NULL) {
                        talloc_free(mem_ctx);
                        return LDB_ERR_OPERATIONS_ERROR;
                }
-               
-               *down_req = *req; /* copy the request */
-               
-               down_req->op.mod.message = msg = ldb_msg_copy_shallow(down_req, req->op.mod.message);
-               
-               if (down_req->op.mod.message == NULL) {
-                       talloc_free(mem_ctx);
-                       return LDB_ERR_OPERATIONS_ERROR;
-               }
-               
+
                ret = fix_attributes(module->ldb, schema, msg);
                if (ret != LDB_SUCCESS) {
                        talloc_free(mem_ctx);
                        return ret;
                }
 
-               ret = objectclass_sort(module, schema, msg, mem_ctx, objectclass_element, &sorted);
+               ret = objectclass_sort(module, schema, mem_ctx, objectclass_element, &sorted);
                if (ret != LDB_SUCCESS) {
+                       talloc_free(mem_ctx);
                        return ret;
                }
 
@@ -719,9 +740,21 @@ static int objectclass_modify(struct ldb_module *module, struct ldb_request *req
 
                /* Move from the linked list back into an ldb msg */
                for (current = sorted; current; current = current->next) {
-                       ret = ldb_msg_add_string(msg, "objectClass", current->objectclass->lDAPDisplayName);
+                       /* copy the value as this string is on the schema
+                        * context and we can't rely on it not changing
+                        * before the operation is over */
+                       value = talloc_strdup(msg,
+                                       current->objectclass->lDAPDisplayName);
+                       if (value == NULL) {
+                               ldb_oom(module->ldb);
+                               talloc_free(mem_ctx);
+                               return LDB_ERR_OPERATIONS_ERROR;
+                       }
+                       ret = ldb_msg_add_string(msg, "objectClass", value);
                        if (ret != LDB_SUCCESS) {
-                               ldb_set_errstring(module->ldb, "objectclass: could not re-add sorted objectclass to modify msg");
+                               ldb_set_errstring(module->ldb,
+                                       "objectclass: could not re-add sorted "
+                                       "objectclass to modify msg");
                                talloc_free(mem_ctx);
                                return ret;
                        }
@@ -731,130 +764,121 @@ static int objectclass_modify(struct ldb_module *module, struct ldb_request *req
 
                ret = ldb_msg_sanity_check(module->ldb, msg);
                if (ret != LDB_SUCCESS) {
-                       talloc_free(mem_ctx);
                        return ret;
                }
-               
-               /* go on with the call chain */
-               ret = ldb_next_request(module, down_req);
-               
-               /* do not free down_req as the call results may be linked to it,
-                * it will be freed when the upper level request get freed */
-               if (ret == LDB_SUCCESS) {
-                       req->handle = down_req->handle;
+
+               ret = ldb_build_mod_req(&down_req, module->ldb, ac,
+                                       msg,
+                                       req->controls,
+                                       ac, oc_op_callback,
+                                       req);
+               if (ret != LDB_SUCCESS) {
+                       return ret;
                }
-               return ret;
-       }
+
+               /* go on with the call chain */
+               return ldb_next_request(module, down_req);
        }
 
        /* This isn't the default branch of the switch, but a 'in any
         * other case'.  When a delete isn't for all objectClasses for
         * example
         */
-       {
-               struct ldb_handle *h;
-               struct oc_context *ac;
-               
-               h = oc_init_handle(req, module);
-               if (!h) {
-                       return LDB_ERR_OPERATIONS_ERROR;
-               }
-               ac = talloc_get_type(h->private_data, struct oc_context);
-               
-               /* return or own handle to deal with this call */
-               req->handle = h;
-               
-               /* prepare the first operation */
-               ac->down_req = talloc(ac, struct ldb_request);
-               if (ac->down_req == NULL) {
-                       ldb_oom(ac->module->ldb);
-                       return LDB_ERR_OPERATIONS_ERROR;
-               }
-               
-               *(ac->down_req) = *req; /* copy the request */
-               
-               ac->down_req->op.mod.message = msg = ldb_msg_copy_shallow(ac->down_req, req->op.mod.message);
-               
-               if (ac->down_req->op.mod.message == NULL) {
-                       ldb_oom(ac->module->ldb);
-                       return LDB_ERR_OPERATIONS_ERROR;
-               }
-               
-               ret = fix_attributes(ac->module->ldb, schema, msg);
-               if (ret != LDB_SUCCESS) {
-                       ldb_oom(ac->module->ldb);
-                       return ret;
-               }
 
-               ac->down_req->context = NULL;
-               ac->down_req->callback = NULL;
-               ldb_set_timeout_from_prev_req(module->ldb, req, ac->down_req);
-               
-               ac->step = OC_DO_REQ;
+       msg = ldb_msg_copy_shallow(ac, req->op.mod.message);
+       if (msg == NULL) {
+               ldb_oom(module->ldb);
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
 
-               return ldb_next_request(module, ac->down_req);
+       ret = fix_attributes(module->ldb, schema, msg);
+       if (ret != LDB_SUCCESS) {
+               ldb_oom(ac->module->ldb);
+               return ret;
+       }
+
+       ret = ldb_build_mod_req(&down_req, module->ldb, ac,
+                               msg,
+                               req->controls,
+                               ac, oc_modify_callback,
+                               req);
+       if (ret != LDB_SUCCESS) {
+               return ret;
        }
+
+       return ldb_next_request(module, down_req);
 }
 
-static int objectclass_search_self(struct ldb_handle *h) 
+static int oc_modify_callback(struct ldb_request *req, struct ldb_reply *ares)
 {
-       int ret;
-       struct oc_context *ac;
        static const char * const attrs[] = { "objectClass", NULL };
+       struct ldb_request *search_req;
+       struct oc_context *ac;
+       int ret;
 
-       ac = talloc_get_type(h->private_data, struct oc_context);
+       ac = talloc_get_type(req->context, struct oc_context);
 
-       ret = ldb_build_search_req(&ac->search_req, ac->module->ldb,
-                                  ac, ac->orig_req->op.mod.message->dn, LDB_SCOPE_BASE,
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
+
+       if (ares->type != LDB_REPLY_DONE) {
+               talloc_free(ares);
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+
+       ret = ldb_build_search_req(&search_req, ac->module->ldb, ac,
+                                  ac->req->op.mod.message->dn, LDB_SCOPE_BASE,
                                   "(objectClass=*)",
                                   attrs, NULL, 
-                                  ac, get_search_callback);
-
+                                  ac, get_search_callback,
+                                  ac->req);
        if (ret != LDB_SUCCESS) {
-               return ret;
+               return ldb_module_done(ac->req, NULL, NULL, ret);
        }
 
-       ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->search_req);
-
-       ac->step = OC_SEARCH_SELF;
+       ac->step_fn = objectclass_do_mod;
 
-       return ldb_next_request(ac->module, ac->search_req);
+       ret = ldb_next_request(ac->module, search_req);
+       if (ret != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, NULL, NULL, ret);
+       }
+       return LDB_SUCCESS;
 }
 
-static int objectclass_do_mod(struct ldb_handle *h) {
+static int objectclass_do_mod(struct oc_context *ac)
+{
 
        const struct dsdb_schema *schema;
-       struct oc_context *ac;
+       struct ldb_request *mod_req;
+       char *value;
        struct ldb_message_element *objectclass_element;
        struct ldb_message *msg;
        TALLOC_CTX *mem_ctx;
        struct class_list *sorted, *current;
        int ret;
-      
-       ac = talloc_get_type(h->private_data, struct oc_context);
-       schema = dsdb_get_schema(ac->module->ldb);
 
-       mem_ctx = talloc_new(ac);
-       if (mem_ctx == NULL) {
+       if (ac->search_res == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
+       schema = dsdb_get_schema(ac->module->ldb);
 
-       ac->mod_req = talloc(ac, struct ldb_request);
-       if (ac->mod_req == NULL) {
-               talloc_free(mem_ctx);
+       mem_ctx = talloc_new(ac);
+       if (mem_ctx == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       ac->mod_req->operation = LDB_MODIFY;
-       ac->mod_req->controls = NULL;
-       ac->mod_req->context = ac;
-       ac->mod_req->callback = NULL;
-       ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->mod_req);
-       
        /* use a new message structure */
-       ac->mod_req->op.mod.message = msg = ldb_msg_new(ac->mod_req);
+       msg = ldb_msg_new(ac);
        if (msg == NULL) {
-               ldb_set_errstring(ac->module->ldb, "objectclass: could not create new modify msg");
+               ldb_set_errstring(ac->module->ldb,
+                       "objectclass: could not create new modify msg");
                talloc_free(mem_ctx);
                return LDB_ERR_OPERATIONS_ERROR;
        }
@@ -869,9 +893,9 @@ static int objectclass_do_mod(struct ldb_handle *h) {
        }
        
        /* modify dn */
-       msg->dn = ac->orig_req->op.mod.message->dn;
+       msg->dn = ac->req->op.mod.message->dn;
 
-       ret = objectclass_sort(ac->module, schema, msg, mem_ctx, objectclass_element, &sorted);
+       ret = objectclass_sort(ac->module, schema, mem_ctx, objectclass_element, &sorted);
        if (ret != LDB_SUCCESS) {
                return ret;
        }
@@ -889,7 +913,12 @@ static int objectclass_do_mod(struct ldb_handle *h) {
        
        /* Move from the linked list back into an ldb msg */
        for (current = sorted; current; current = current->next) {
-               ret = ldb_msg_add_string(msg, "objectClass", current->objectclass->lDAPDisplayName);
+               value = talloc_strdup(msg, current->objectclass->lDAPDisplayName);
+               if (value == NULL) {
+                       ldb_oom(ac->module->ldb);
+                       return LDB_ERR_OPERATIONS_ERROR;
+               }
+               ret = ldb_msg_add_string(msg, "objectClass", value);
                if (ret != LDB_SUCCESS) {
                        ldb_set_errstring(ac->module->ldb, "objectclass: could not re-add sorted objectclass to modify msg");
                        talloc_free(mem_ctx);
@@ -903,33 +932,38 @@ static int objectclass_do_mod(struct ldb_handle *h) {
                return ret;
        }
 
-
-       h->state = LDB_ASYNC_INIT;
-       h->status = LDB_SUCCESS;
-
-       ac->step = OC_DO_MOD;
+       ret = ldb_build_mod_req(&mod_req, ac->module->ldb, ac,
+                               msg,
+                               ac->req->controls,
+                               ac, oc_op_callback,
+                               ac->req);
+       if (ret != LDB_SUCCESS) {
+               talloc_free(mem_ctx);
+               return ret;
+       }
 
        talloc_free(mem_ctx);
-       /* perform the search */
-       return ldb_next_request(ac->module, ac->mod_req);
+       /* perform the modify */
+       return ldb_next_request(ac->module, mod_req);
 }
 
+static int objectclass_do_rename(struct oc_context *ac);
+
 static int objectclass_rename(struct ldb_module *module, struct ldb_request *req)
 {
-
        static const char * const attrs[] = { NULL };
 
-       struct ldb_handle *h;
+       struct ldb_request *search_req;
        struct oc_context *ac;
        struct ldb_dn *parent_dn;
        int ret;
-       
+
        ldb_debug(module->ldb, LDB_DEBUG_TRACE, "objectclass_rename\n");
 
        if (ldb_dn_is_special(req->op.rename.newdn)) { /* do not manipulate our control entries */
                return ldb_next_request(module, req);
        }
-       
+
        /* Firstly ensure we are not trying to rename it to be a child of itself */
        if ((ldb_dn_compare_base(req->op.rename.olddn, req->op.rename.newdn) == 0) 
            && (ldb_dn_compare(req->op.rename.olddn, req->op.rename.newdn) != 0)) {
@@ -938,65 +972,50 @@ static int objectclass_rename(struct ldb_module *module, struct ldb_request *req
                return LDB_ERR_UNWILLING_TO_PERFORM;
        }
 
-       h = oc_init_handle(req, module);
-       if (!h) {
+       ac = oc_init_context(module, req);
+       if (ac == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       ac = talloc_get_type(h->private_data, struct oc_context);
-       
-       /* return or own handle to deal with this call */
-       req->handle = h;
 
-       parent_dn = ldb_dn_get_parent(ac, ac->orig_req->op.rename.newdn);
+       parent_dn = ldb_dn_get_parent(ac, req->op.rename.newdn);
        if (parent_dn == NULL) {
                ldb_oom(module->ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       ret = ldb_build_search_req(&ac->search_req, module->ldb,
+       ret = ldb_build_search_req(&search_req, module->ldb,
                                   ac, parent_dn, LDB_SCOPE_BASE,
                                   "(objectClass=*)",
                                   attrs, NULL, 
-                                  ac, get_search_callback);
+                                  ac, get_search_callback,
+                                  req);
        if (ret != LDB_SUCCESS) {
                return ret;
        }
-       talloc_steal(ac->search_req, parent_dn);
-       ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->search_req);
 
-       ac->step = OC_SEARCH_RENAME_PARENT;
+       ac->step_fn = objectclass_do_rename;
 
-       return ldb_next_request(ac->module, ac->search_req);
+       return ldb_next_request(ac->module, search_req);
 }
 
-static int objectclass_do_rename(struct ldb_handle *h) 
+static int objectclass_do_rename(struct oc_context *ac)
 {
-       struct oc_context *ac;
+       struct ldb_request *rename_req;
+       struct ldb_dn *fixed_dn;
        int ret;
-      
-       ac = talloc_get_type(h->private_data, struct oc_context);
 
-       ac->rename_req = talloc(ac, struct ldb_request);
-       if (ac->rename_req == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       *ac->rename_req = *ac->orig_req;
-
-       ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->rename_req);
-       
        /* Check we have a valid parent */
        if (ac->search_res == NULL) {
                ldb_asprintf_errstring(ac->module->ldb, "objectclass: Cannot rename %s, parent does not exist!", 
-                                      ldb_dn_get_linearized(ac->orig_req->op.rename.newdn));
+                                      ldb_dn_get_linearized(ac->req->op.rename.newdn));
                return LDB_ERR_UNWILLING_TO_PERFORM;
        }
        
-       /* Fix up the DN to be in the standard form, taking particular care to match the parent DN */
-       ret = fix_dn(ac->rename_req, 
-                    ac->orig_req->op.rename.newdn, 
-                    ac->search_res->message->dn, 
-                    &ac->rename_req->op.rename.newdn);
-
+       /* Fix up the DN to be in the standard form,
+        * taking particular care to match the parent DN */
+       ret = fix_dn(ac,
+                    ac->req->op.rename.newdn,
+                    ac->search_res->message->dn,
+                    &fixed_dn);
        if (ret != LDB_SUCCESS) {
                return ret;
        }
@@ -1005,197 +1024,17 @@ static int objectclass_do_rename(struct ldb_handle *h)
         * by reading the allowedChildClasses and
         * allowedChildClasssesEffective attributes */
 
-       h->state = LDB_ASYNC_INIT;
-       h->status = LDB_SUCCESS;
-
-       ac->step = OC_DO_RENAME;
-
-       /* perform the rename */
-       return ldb_next_request(ac->module, ac->rename_req);
-}
-
-static int oc_wait(struct ldb_handle *handle) {
-       struct oc_context *ac;
-       int ret;
-    
-       if (!handle || !handle->private_data) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       if (handle->state == LDB_ASYNC_DONE) {
-               return handle->status;
-       }
-
-       handle->state = LDB_ASYNC_PENDING;
-       handle->status = LDB_SUCCESS;
-
-       ac = talloc_get_type(handle->private_data, struct oc_context);
-
-       switch (ac->step) {
-       case OC_DO_REQ:
-               ret = ldb_wait(ac->down_req->handle, LDB_WAIT_NONE);
-
-               if (ret != LDB_SUCCESS) {
-                       handle->status = ret;
-                       goto done;
-               }
-               if (ac->down_req->handle->status != LDB_SUCCESS) {
-                       handle->status = ac->down_req->handle->status;
-                       goto done;
-               }
-
-               if (ac->down_req->handle->state != LDB_ASYNC_DONE) {
-                       return LDB_SUCCESS;
-               }
-
-               /* mods done, go on */
-               return objectclass_search_self(handle);
-
-       case OC_SEARCH_SELF:
-               ret = ldb_wait(ac->search_req->handle, LDB_WAIT_NONE);
-
-               if (ret != LDB_SUCCESS) {
-                       handle->status = ret;
-                       goto done;
-               }
-               if (ac->search_req->handle->status != LDB_SUCCESS) {
-                       handle->status = ac->search_req->handle->status;
-                       goto done;
-               }
-
-               if (ac->search_req->handle->state != LDB_ASYNC_DONE) {
-                       return LDB_SUCCESS;
-               }
-
-               /* self search done, go on */
-               return objectclass_do_mod(handle);
-
-       case OC_DO_MOD:
-               ret = ldb_wait(ac->mod_req->handle, LDB_WAIT_NONE);
-
-               if (ret != LDB_SUCCESS) {
-                       handle->status = ret;
-                       goto done;
-               }
-               if (ac->mod_req->handle->status != LDB_SUCCESS) {
-                       handle->status = ac->mod_req->handle->status;
-                       goto done;
-               }
-
-               if (ac->mod_req->handle->state != LDB_ASYNC_DONE) {
-                       return LDB_SUCCESS;
-               }
-
-               break;
-               
-       case OC_SEARCH_ADD_PARENT:
-               ret = ldb_wait(ac->search_req->handle, LDB_WAIT_NONE);
-
-               if (ret != LDB_SUCCESS && ret != LDB_ERR_NO_SUCH_OBJECT) {
-                       handle->status = ret;
-                       goto done;
-               }
-               if (ac->search_req->handle->status != LDB_SUCCESS
-                   && ac->search_req->handle->status != LDB_ERR_NO_SUCH_OBJECT) {
-                       handle->status = ac->search_req->handle->status;
-                       goto done;
-               }
-
-               if (ac->search_req->handle->state != LDB_ASYNC_DONE) {
-                       return LDB_SUCCESS;
-               }
-
-               /* parent search done, go on */
-               return objectclass_do_add(handle);
-
-       case OC_DO_ADD:
-               ret = ldb_wait(ac->add_req->handle, LDB_WAIT_NONE);
-
-               if (ret != LDB_SUCCESS) {
-                       handle->status = ret;
-                       goto done;
-               }
-               if (ac->add_req->handle->status != LDB_SUCCESS) {
-                       handle->status = ac->add_req->handle->status;
-                       goto done;
-               }
-
-               if (ac->add_req->handle->state != LDB_ASYNC_DONE) {
-                       return LDB_SUCCESS;
-               }
-
-               break;
-               
-       case OC_SEARCH_RENAME_PARENT:
-               ret = ldb_wait(ac->search_req->handle, LDB_WAIT_NONE);
-
-               if (ret != LDB_SUCCESS && ret != LDB_ERR_NO_SUCH_OBJECT) {
-                       handle->status = ret;
-                       goto done;
-               }
-               if (ac->search_req->handle->status != LDB_SUCCESS && ac->search_req->handle->status != LDB_ERR_NO_SUCH_OBJECT) {
-                       handle->status = ac->search_req->handle->status;
-                       goto done;
-               }
-
-               if (ac->search_req->handle->state != LDB_ASYNC_DONE) {
-                       return LDB_SUCCESS;
-               }
-
-               /* parent search done, go on */
-               return objectclass_do_rename(handle);
-
-       case OC_DO_RENAME:
-               ret = ldb_wait(ac->rename_req->handle, LDB_WAIT_NONE);
-
-               if (ret != LDB_SUCCESS) {
-                       handle->status = ret;
-                       goto done;
-               }
-               if (ac->rename_req->handle->status != LDB_SUCCESS) {
-                       handle->status = ac->rename_req->handle->status;
-                       goto done;
-               }
-
-               if (ac->rename_req->handle->state != LDB_ASYNC_DONE) {
-                       return LDB_SUCCESS;
-               }
-
-               break;
-               
-       default:
-               ret = LDB_ERR_OPERATIONS_ERROR;
-               goto done;
-       }
-
-       ret = LDB_SUCCESS;
-
-done:
-       handle->state = LDB_ASYNC_DONE;
-       return ret;
-}
-
-static int oc_wait_all(struct ldb_handle *handle) {
-
-       int ret;
-
-       while (handle->state != LDB_ASYNC_DONE) {
-               ret = oc_wait(handle);
-               if (ret != LDB_SUCCESS) {
-                       return ret;
-               }
+       ret = ldb_build_rename_req(&rename_req, ac->module->ldb, ac,
+                                  ac->req->op.rename.olddn, fixed_dn,
+                                  ac->req->controls,
+                                  ac, oc_op_callback,
+                                  ac->req);
+       if (ret != LDB_SUCCESS) {
+               return ret;
        }
 
-       return handle->status;
-}
-
-static int objectclass_wait(struct ldb_handle *handle, enum ldb_wait_type type)
-{
-       if (type == LDB_WAIT_ALL) {
-               return oc_wait_all(handle);
-       } else {
-               return oc_wait(handle);
-       }
+       /* perform the rename */
+       return ldb_next_request(ac->module, rename_req);
 }
 
 _PUBLIC_ const struct ldb_module_ops ldb_objectclass_module_ops = {
@@ -1203,5 +1042,4 @@ _PUBLIC_ const struct ldb_module_ops ldb_objectclass_module_ops = {
        .add           = objectclass_add,
        .modify        = objectclass_modify,
        .rename        = objectclass_rename,
-       .wait          = objectclass_wait
 };
index f62839389d2c6b70274da08e281dfb3af9ada880..054905992deeee44a46596a2e6ccbf199d9cda4e 100644 (file)
@@ -1,9 +1,9 @@
 /* 
    ldb database library
 
-   Copyright (C) Simo Sorce  2004-2006
    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005
    Copyright (C) Andrew Tridgell 2005
+   Copyright (C) Simo Sorce  2004-2008
 
      ** NOTE! The following LGPL license applies to the ldb
      ** library. This does NOT imply that all of Samba is released
@@ -103,6 +103,36 @@ static int add_uint64_element(struct ldb_message *msg, const char *attr, uint64_
        return 0;
 }
 
+struct og_context {
+       struct ldb_module *module;
+       struct ldb_request *req;
+};
+
+static int og_op_callback(struct ldb_request *req, struct ldb_reply *ares)
+{
+       struct og_context *ac;
+
+       ac = talloc_get_type(req->context, struct og_context);
+
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
+
+       if (ares->type != LDB_REPLY_DONE) {
+               talloc_free(ares);
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+
+       return ldb_module_done(ac->req, ares->controls,
+                               ares->response, ares->error);
+}
+
 /* add_record: add objectGUID attribute */
 static int objectguid_add(struct ldb_module *module, struct ldb_request *req)
 {
@@ -115,6 +145,7 @@ static int objectguid_add(struct ldb_module *module, struct ldb_request *req)
        enum ndr_err_code ndr_err;
        int ret;
        time_t t = time(NULL);
+       struct og_context *ac;
 
        ldb_debug(module->ldb, LDB_DEBUG_TRACE, "objectguid_add_record\n");
 
@@ -127,15 +158,15 @@ static int objectguid_add(struct ldb_module *module, struct ldb_request *req)
                return ldb_next_request(module, req);
        }
 
-       down_req = talloc(req, struct ldb_request);
-       if (down_req == NULL) {
+       ac = talloc(req, struct og_context);
+       if (ac == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
-
-       *down_req = *req;
+       ac->module = module;
+       ac->req = req;
 
        /* we have to copy the message as the caller might have it as a const */
-       down_req->op.add.message = msg = ldb_msg_copy_shallow(down_req, req->op.add.message);
+       msg = ldb_msg_copy_shallow(ac, req->op.add.message);
        if (msg == NULL) {
                talloc_free(down_req);
                return LDB_ERR_OPERATIONS_ERROR;
@@ -149,44 +180,41 @@ static int objectguid_add(struct ldb_module *module, struct ldb_request *req)
                                       &guid,
                                       (ndr_push_flags_fn_t)ndr_push_GUID);
        if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
-               talloc_free(down_req);
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
        ret = ldb_msg_add_value(msg, "objectGUID", &v, NULL);
        if (ret) {
-               talloc_free(down_req);
                return ret;
        }
        
        if (add_time_element(msg, "whenCreated", t) != 0 ||
            add_time_element(msg, "whenChanged", t) != 0) {
-               talloc_free(down_req);
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
        /* Get a sequence number from the backend */
+       /* FIXME: ldb_sequence_number is still SYNC now, when this changes,
+        * make sure this function is split and a callback is used */
        ret = ldb_sequence_number(module->ldb, LDB_SEQ_NEXT, &seq_num);
        if (ret == LDB_SUCCESS) {
                if (add_uint64_element(msg, "uSNCreated", seq_num) != 0 ||
                    add_uint64_element(msg, "uSNChanged", seq_num) != 0) {
-                       talloc_free(down_req);
                        return LDB_ERR_OPERATIONS_ERROR;
                }
        }
 
-       ldb_set_timeout_from_prev_req(module->ldb, req, down_req);
-
-       /* go on with the call chain */
-       ret = ldb_next_request(module, down_req);
-
-       /* do not free down_req as the call results may be linked to it,
-        * it will be freed when the upper level request get freed */
-       if (ret == LDB_SUCCESS) {
-               req->handle = down_req->handle;
+       ret = ldb_build_add_req(&down_req, module->ldb, ac,
+                               msg,
+                               req->controls,
+                               ac, og_op_callback,
+                               req);
+       if (ret != LDB_SUCCESS) {
+               return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       return ret;
+       /* go on with the call chain */
+       return ldb_next_request(module, down_req);
 }
 
 /* modify_record: update timestamps */
@@ -197,6 +225,7 @@ static int objectguid_modify(struct ldb_module *module, struct ldb_request *req)
        int ret;
        time_t t = time(NULL);
        uint64_t seq_num;
+       struct og_context *ac;
 
        ldb_debug(module->ldb, LDB_DEBUG_TRACE, "objectguid_add_record\n");
 
@@ -205,22 +234,20 @@ static int objectguid_modify(struct ldb_module *module, struct ldb_request *req)
                return ldb_next_request(module, req);
        }
 
-       down_req = talloc(req, struct ldb_request);
-       if (down_req == NULL) {
+       ac = talloc(req, struct og_context);
+       if (ac == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
-
-       *down_req = *req;
+       ac->module = module;
+       ac->req = req;
 
        /* we have to copy the message as the caller might have it as a const */
-       down_req->op.mod.message = msg = ldb_msg_copy_shallow(down_req, req->op.mod.message);
+       msg = ldb_msg_copy_shallow(ac, req->op.mod.message);
        if (msg == NULL) {
-               talloc_free(down_req);
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
        if (add_time_element(msg, "whenChanged", t) != 0) {
-               talloc_free(down_req);
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
@@ -228,23 +255,21 @@ static int objectguid_modify(struct ldb_module *module, struct ldb_request *req)
        ret = ldb_sequence_number(module->ldb, LDB_SEQ_NEXT, &seq_num);
        if (ret == LDB_SUCCESS) {
                if (add_uint64_element(msg, "uSNChanged", seq_num) != 0) {
-                       talloc_free(down_req);
                        return LDB_ERR_OPERATIONS_ERROR;
                }
        }
 
-       ldb_set_timeout_from_prev_req(module->ldb, req, down_req);
-
-       /* go on with the call chain */
-       ret = ldb_next_request(module, down_req);
-
-       /* do not free down_req as the call results may be linked to it,
-        * it will be freed when the upper level request get freed */
-       if (ret == LDB_SUCCESS) {
-               req->handle = down_req->handle;
+       ret = ldb_build_mod_req(&down_req, module->ldb, ac,
+                               msg,
+                               req->controls,
+                               ac, og_op_callback,
+                               req);
+       if (ret != LDB_SUCCESS) {
+               return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       return ret;
+       /* go on with the call chain */
+       return ldb_next_request(module, down_req);
 }
 
 _PUBLIC_ const struct ldb_module_ops ldb_objectguid_module_ops = {
index 0cd0baf6255750d96228abf994cb83d4fe659fbf..b452b66d569f8057453f1c58014190131d8b7ccb 100644 (file)
@@ -1,4 +1,3 @@
-
 /* 
    Partitions ldb module
 
@@ -43,61 +42,99 @@ struct partition_private_data {
        struct ldb_dn **replicate;
 };
 
+struct part_request {
+       struct ldb_module *module;
+       struct ldb_request *req;
+};
+
 struct partition_context {
        struct ldb_module *module;
-       struct ldb_request *orig_req;
+       struct ldb_request *req;
+       bool got_success;
 
-       struct ldb_request **down_req;
+       struct part_request *part_req;
        int num_requests;
        int finished_requests;
 };
 
-static struct partition_context *partition_init_handle(struct ldb_request *req, struct ldb_module *module)
+static struct partition_context *partition_init_ctx(struct ldb_module *module, struct ldb_request *req)
 {
        struct partition_context *ac;
-       struct ldb_handle *h;
 
-       h = talloc_zero(req, struct ldb_handle);
-       if (h == NULL) {
-               ldb_set_errstring(module->ldb, "Out of Memory");
-               return NULL;
-       }
-
-       h->module = module;
-
-       ac = talloc_zero(h, struct partition_context);
+       ac = talloc_zero(req, struct partition_context);
        if (ac == NULL) {
                ldb_set_errstring(module->ldb, "Out of Memory");
-               talloc_free(h);
                return NULL;
        }
 
-       h->private_data = ac;
-
        ac->module = module;
-       ac->orig_req = req;
-
-       req->handle = h;
+       ac->req = req;
 
        return ac;
 }
 
-static struct ldb_module *make_module_for_next_request(TALLOC_CTX *mem_ctx, 
-                                                      struct ldb_context *ldb,
-                                                      struct ldb_module *module)
+#define PARTITION_FIND_OP(module, op) do { \
+       struct ldb_context *ldbctx = module->ldb; \
+        while (module && module->ops->op == NULL) module = module->next; \
+        if (module == NULL) { \
+                ldb_asprintf_errstring(ldbctx, \
+                       "Unable to find backend operation for " #op ); \
+                return LDB_ERR_OPERATIONS_ERROR; \
+        } \
+} while (0)
+
+/*
+ *    helper functions to call the next module in chain
+ *    */
+
+int partition_request(struct ldb_module *module, struct ldb_request *request)
 {
-       struct ldb_module *current;
-       static const struct ldb_module_ops ops; /* zero */
-       current = talloc_zero(mem_ctx, struct ldb_module);
-       if (current == NULL) {
-               return module;
+       int ret;
+       switch (request->operation) {
+       case LDB_SEARCH:
+               PARTITION_FIND_OP(module, search);
+               ret = module->ops->search(module, request);
+               break;
+       case LDB_ADD:
+               PARTITION_FIND_OP(module, add);
+               ret = module->ops->add(module, request);
+               break;
+       case LDB_MODIFY:
+               PARTITION_FIND_OP(module, modify);
+               ret = module->ops->modify(module, request);
+               break;
+       case LDB_DELETE:
+               PARTITION_FIND_OP(module, del);
+               ret = module->ops->del(module, request);
+               break;
+       case LDB_RENAME:
+               PARTITION_FIND_OP(module, rename);
+               ret = module->ops->rename(module, request);
+               break;
+       case LDB_EXTENDED:
+               PARTITION_FIND_OP(module, extended);
+               ret = module->ops->extended(module, request);
+               break;
+       case LDB_SEQUENCE_NUMBER:
+               PARTITION_FIND_OP(module, sequence_number);
+               ret = module->ops->sequence_number(module, request);
+               break;
+       default:
+               PARTITION_FIND_OP(module, request);
+               ret = module->ops->request(module, request);
+               break;
        }
-       
-       current->ldb = ldb;
-       current->ops = &ops;
-       current->prev = NULL;
-       current->next = module;
-       return current;
+       if (ret == LDB_SUCCESS) {
+               return ret;
+       }
+       if (!ldb_errstring(module->ldb)) {
+               /* Set a default error string, to place the blame somewhere */
+               ldb_asprintf_errstring(module->ldb,
+                                       "error in module %s: %s (%d)",
+                                       module->ops->name,
+                                       ldb_strerror(ret), ret);
+       }
+       return ret;
 }
 
 static struct dsdb_control_current_partition *find_partition(struct partition_private_data *data,
@@ -120,127 +157,206 @@ static struct dsdb_control_current_partition *find_partition(struct partition_pr
 /**
  * fire the caller's callback for every entry, but only send 'done' once.
  */
-static int partition_search_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares)
+static int partition_req_callback(struct ldb_request *req,
+                                 struct ldb_reply *ares)
 {
        struct partition_context *ac;
+       struct ldb_module *module;
+       struct ldb_request *nreq;
+       int ret;
 
-       ac = talloc_get_type(context, struct partition_context);
+       ac = talloc_get_type(req->context, struct partition_context);
 
-       if (ares->type == LDB_REPLY_ENTRY) {
-               return ac->orig_req->callback(ldb, ac->orig_req->context, ares);
-       } else {
-               ac->finished_requests++;
-               if (ac->finished_requests == ac->num_requests) {
-                       return ac->orig_req->callback(ldb, ac->orig_req->context, ares);
-               } else {
-                       talloc_free(ares);
-                       return LDB_SUCCESS;
-               }
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
        }
-}
 
-/**
- * only fire the 'last' callback, and only for START-TLS for now 
- */
-static int partition_other_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares)
-{
-       struct partition_context *ac;
+       if (ares->error != LDB_SUCCESS && !ac->got_success) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
 
-       ac = talloc_get_type(context, struct partition_context);
+       switch (ares->type) {
+       case LDB_REPLY_REFERRAL:
+               /* ignore referrals for now */
+               break;
 
-       if (!ac->orig_req->callback) {
-               talloc_free(ares);
-               return LDB_SUCCESS;
-       }
+       case LDB_REPLY_ENTRY:
+               if (ac->req->operation != LDB_SEARCH) {
+                       ldb_set_errstring(ac->module->ldb,
+                               "partition_req_callback:"
+                               " Unsupported reply type for this request");
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
+               }
+               return ldb_module_send_entry(ac->req, ares->message);
+
+       case LDB_REPLY_DONE:
+               if (ares->error == LDB_SUCCESS) {
+                       ac->got_success = true;
+               }
+               if (ac->req->operation == LDB_EXTENDED) {
+                       /* FIXME: check for ares->response, replmd does not fill it ! */
+                       if (ares->response) {
+                               if (strcmp(ares->response->oid, LDB_EXTENDED_START_TLS_OID) != 0) {
+                                       ldb_set_errstring(ac->module->ldb,
+                                                         "partition_req_callback:"
+                                                         " Unknown extended reply, "
+                                                         "only supports START_TLS");
+                                       talloc_free(ares);
+                                       return ldb_module_done(ac->req, NULL, NULL,
+                                                               LDB_ERR_OPERATIONS_ERROR);
+                               }
+                       }
+               }
 
-       if (!ares 
-           || (ares->type == LDB_REPLY_EXTENDED 
-               && strcmp(ares->response->oid, LDB_EXTENDED_START_TLS_OID))) {
                ac->finished_requests++;
                if (ac->finished_requests == ac->num_requests) {
-                       return ac->orig_req->callback(ldb, ac->orig_req->context, ares);
+                       /* this was the last one, call callback */
+                       return ldb_module_done(ac->req, ares->controls,
+                                              ares->response, 
+                                              ac->got_success?LDB_SUCCESS:ares->error);
+               }
+
+               /* not the last, now call the next one */
+               module = ac->part_req[ac->finished_requests].module;
+               nreq = ac->part_req[ac->finished_requests].req;
+
+               ret = partition_request(module, nreq);
+               if (ret != LDB_SUCCESS) {
+                       talloc_free(ares);
+                       return ldb_module_done(ac->req, NULL, NULL, ret);
                }
-               talloc_free(ares);
-               return LDB_SUCCESS;
+
+               break;
        }
-       ldb_set_errstring(ldb, "partition_other_callback: Unknown reply type, only supports START_TLS");
+
        talloc_free(ares);
-       return LDB_ERR_OPERATIONS_ERROR;
+       return LDB_SUCCESS;
 }
 
-
-static int partition_send_request(struct partition_context *ac, 
+static int partition_prep_request(struct partition_context *ac,
                                  struct dsdb_control_current_partition *partition)
 {
        int ret;
-       struct ldb_module *backend;
        struct ldb_request *req;
 
-       if (partition) {
-               backend = make_module_for_next_request(ac, ac->module->ldb, partition->module);
-       } else {
-               backend = ac->module;
-       }
-
-       ac->down_req = talloc_realloc(ac, ac->down_req, 
-                                       struct ldb_request *, ac->num_requests + 1);
-       if (!ac->down_req) {
+       ac->part_req = talloc_realloc(ac, ac->part_req,
+                                       struct part_request,
+                                       ac->num_requests + 1);
+       if (ac->part_req == NULL) {
                ldb_oom(ac->module->ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       req = ac->down_req[ac->num_requests] = talloc(ac, struct ldb_request);
-       if (req == NULL) {
-               ldb_oom(ac->module->ldb);
-               return LDB_ERR_OPERATIONS_ERROR;
+
+       switch (ac->req->operation) {
+       case LDB_SEARCH:
+               ret = ldb_build_search_req_ex(&req, ac->module->ldb,
+                                       ac->part_req,
+                                       ac->req->op.search.base,
+                                       ac->req->op.search.scope,
+                                       ac->req->op.search.tree,
+                                       ac->req->op.search.attrs,
+                                       ac->req->controls,
+                                       ac, partition_req_callback,
+                                       ac->req);
+               break;
+       case LDB_ADD:
+               ret = ldb_build_add_req(&req, ac->module->ldb, ac->part_req,
+                                       ac->req->op.add.message,
+                                       ac->req->controls,
+                                       ac, partition_req_callback,
+                                       ac->req);
+               break;
+       case LDB_MODIFY:
+               ret = ldb_build_mod_req(&req, ac->module->ldb, ac->part_req,
+                                       ac->req->op.mod.message,
+                                       ac->req->controls,
+                                       ac, partition_req_callback,
+                                       ac->req);
+               break;
+       case LDB_DELETE:
+               ret = ldb_build_del_req(&req, ac->module->ldb, ac->part_req,
+                                       ac->req->op.del.dn,
+                                       ac->req->controls,
+                                       ac, partition_req_callback,
+                                       ac->req);
+               break;
+       case LDB_RENAME:
+               ret = ldb_build_rename_req(&req, ac->module->ldb, ac->part_req,
+                                       ac->req->op.rename.olddn,
+                                       ac->req->op.rename.newdn,
+                                       ac->req->controls,
+                                       ac, partition_req_callback,
+                                       ac->req);
+               break;
+       case LDB_EXTENDED:
+               ret = ldb_build_extended_req(&req, ac->module->ldb,
+                                       ac->part_req,
+                                       ac->req->op.extended.oid,
+                                       ac->req->op.extended.data,
+                                       ac->req->controls,
+                                       ac, partition_req_callback,
+                                       ac->req);
+               break;
+       default:
+               ldb_set_errstring(ac->module->ldb,
+                                 "Unsupported request type!");
+               ret = LDB_ERR_UNWILLING_TO_PERFORM;
        }
-       
-       *req = *ac->orig_req; /* copy the request */
 
-       if (req->controls) {
-               req->controls
-                       = talloc_memdup(req,
-                                       ac->orig_req->controls, talloc_get_size(ac->orig_req->controls));
+       if (ret != LDB_SUCCESS) {
+               return ret;
+       }
+
+       ac->part_req[ac->num_requests].req = req;
+
+       if (ac->req->controls) {
+               req->controls = talloc_memdup(req, ac->req->controls,
+                                       talloc_get_size(ac->req->controls));
                if (req->controls == NULL) {
                        ldb_oom(ac->module->ldb);
                        return LDB_ERR_OPERATIONS_ERROR;
                }
        }
 
-       if (req->operation == LDB_SEARCH) {
-               /* If the search is for 'more' than this partition,
-                * then change the basedn, so a remote LDAP server
-                * doesn't object */
-               if (partition) {
-                       if (ldb_dn_compare_base(partition->dn, req->op.search.base) != 0) {
-                               req->op.search.base = partition->dn;
-                       }
-               } else {
-                       req->op.search.base = NULL;
-               }
-               req->callback = partition_search_callback;
-               req->context = ac;
-       } else {
-               req->callback = partition_other_callback;
-               req->context = ac;
-       }
-
        if (partition) {
-               ret = ldb_request_add_control(req, DSDB_CONTROL_CURRENT_PARTITION_OID, false, partition);
+               ac->part_req[ac->num_requests].module = partition->module;
+
+               ret = ldb_request_add_control(req,
+                                       DSDB_CONTROL_CURRENT_PARTITION_OID,
+                                       false, partition);
                if (ret != LDB_SUCCESS) {
                        return ret;
                }
-       }
 
-       /* Spray off search requests the backend */
-       ret = ldb_next_request(backend, req);
-       if (ret != LDB_SUCCESS) {
-               return ret;
+               if (req->operation == LDB_SEARCH) {
+                       /* If the search is for 'more' than this partition,
+                        * then change the basedn, so a remote LDAP server
+                        * doesn't object */
+                       if (ldb_dn_compare_base(partition->dn,
+                                               req->op.search.base) != 0) {
+                               req->op.search.base = partition->dn;
+                       }
+               }
+
+       } else {
+               /* make sure you put the NEXT module here, or
+                * partition_request() will simply loop forever on itself */
+               ac->part_req[ac->num_requests].module = ac->module->next;
        }
 
        ac->num_requests++;
+
        return LDB_SUCCESS;
 }
 
+static int partition_call_first(struct partition_context *ac)
+{
+       return partition_request(ac->part_req[0].module, ac->part_req[0].req);
+}
+
 /**
  * Send a request down to all the partitions
  */
@@ -251,17 +367,19 @@ static int partition_send_all(struct ldb_module *module,
        int i;
        struct partition_private_data *data = talloc_get_type(module->private_data, 
                                                              struct partition_private_data);
-       int ret = partition_send_request(ac, NULL);
+       int ret = partition_prep_request(ac, NULL);
        if (ret != LDB_SUCCESS) {
                return ret;
        }
        for (i=0; data && data->partitions && data->partitions[i]; i++) {
-               ret = partition_send_request(ac, data->partitions[i]);
+               ret = partition_prep_request(ac, data->partitions[i]);
                if (ret != LDB_SUCCESS) {
                        return ret;
                }
        }
-       return LDB_SUCCESS;
+
+       /* fire the first one */
+       return partition_call_first(ac);
 }
 
 /**
@@ -270,21 +388,23 @@ static int partition_send_all(struct ldb_module *module,
  */
 static int partition_replicate(struct ldb_module *module, struct ldb_request *req, struct ldb_dn *dn) 
 {
+       struct partition_context *ac;
        unsigned i;
        int ret;
        struct dsdb_control_current_partition *partition;
-       struct ldb_module *backend;
        struct partition_private_data *data = talloc_get_type(module->private_data, 
                                                              struct partition_private_data);
+       if (!data || !data->partitions) {
+               return ldb_next_request(module, req);
+       }
        
        if (req->operation != LDB_SEARCH) {
                /* Is this a special DN, we need to replicate to every backend? */
                for (i=0; data->replicate && data->replicate[i]; i++) {
                        if (ldb_dn_compare(data->replicate[i], 
                                           dn) == 0) {
-                               struct partition_context *ac;
                                
-                               ac = partition_init_handle(req, module);
+                               ac = partition_init_ctx(module, req);
                                if (!ac) {
                                        return LDB_ERR_OPERATIONS_ERROR;
                                }
@@ -310,18 +430,19 @@ static int partition_replicate(struct ldb_module *module, struct ldb_request *re
                return ldb_next_request(module, req);
        }
 
-       backend = make_module_for_next_request(req, module->ldb, partition->module);
-       if (!backend) {
+       ac = partition_init_ctx(module, req);
+       if (!ac) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       ret = ldb_request_add_control(req, DSDB_CONTROL_CURRENT_PARTITION_OID, false, partition);
+       /* we need to add a control but we never touch the original request */
+       ret = partition_prep_request(ac, partition);
        if (ret != LDB_SUCCESS) {
                return ret;
        }
 
-       /* issue request */
-       return ldb_next_request(backend, req);
+       /* fire the first one */
+       return partition_call_first(ac);
 }
 
 /* search */
@@ -336,6 +457,7 @@ static int partition_search(struct ldb_module *module, struct ldb_request *req)
 
        /* (later) consider if we should be searching multiple
         * partitions (for 'invisible' partition behaviour */
+
        struct ldb_control *search_control = ldb_request_get_control(req, LDB_CONTROL_SEARCH_OPTIONS_OID);
        struct ldb_control *domain_scope_control = ldb_request_get_control(req, LDB_CONTROL_DOMAIN_SCOPE_OID);
        
@@ -350,6 +472,14 @@ static int partition_search(struct ldb_module *module, struct ldb_request *req)
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
+       /*
+        * for now pass down the LDB_CONTROL_SEARCH_OPTIONS_OID control
+        * down as uncritical to make windows 2008 dcpromo happy.
+        */
+       if (search_control) {
+               search_control->critical = 0;
+       }
+
        /* TODO:
           Generate referrals (look for a partition under this DN) if we don't have the above control specified
        */
@@ -366,7 +496,7 @@ static int partition_search(struct ldb_module *module, struct ldb_request *req)
                                return LDB_ERR_OPERATIONS_ERROR;
                        }
                }
-               ac = partition_init_handle(req, module);
+               ac = partition_init_ctx(module, req);
                if (!ac) {
                        return LDB_ERR_OPERATIONS_ERROR;
                }
@@ -376,13 +506,41 @@ static int partition_search(struct ldb_module *module, struct ldb_request *req)
                        return partition_send_all(module, ac, req);
                }
                for (i=0; data && data->partitions && data->partitions[i]; i++) {
-                       /* Find all partitions under the search base */
-                       if (ldb_dn_compare_base(req->op.search.base, data->partitions[i]->dn) == 0) {
-                               ret = partition_send_request(ac, data->partitions[i]);
+                       bool match = false, stop = false;
+                       /* Find all partitions under the search base 
+                          
+                          we match if:
+
+                             1) the DN we are looking for exactly matches the partition
+                            or
+                             2) the DN we are looking for is a parent of the partition and it isn't
+                                 a scope base search
+                             or
+                             3) the DN we are looking for is a child of the partition
+                        */
+                       if (ldb_dn_compare(data->partitions[i]->dn, req->op.search.base) == 0) {
+                               match = true;
+                               if (req->op.search.scope == LDB_SCOPE_BASE) {
+                                       stop = true;
+                               }
+                       }
+                       if (!match && 
+                           (ldb_dn_compare_base(req->op.search.base, data->partitions[i]->dn) == 0 &&
+                            req->op.search.scope != LDB_SCOPE_BASE)) {
+                               match = true;
+                       }
+                       if (!match &&
+                           ldb_dn_compare_base(data->partitions[i]->dn, req->op.search.base) == 0) {
+                               match = true;
+                               stop = true; /* note that this relies on partition ordering */
+                       }
+                       if (match) {
+                               ret = partition_prep_request(ac, data->partitions[i]);
                                if (ret != LDB_SUCCESS) {
                                        return ret;
                                }
                        }
+                       if (stop) break;
                }
 
                /* Perhaps we didn't match any partitions.  Try the main partition, only */
@@ -390,8 +548,10 @@ static int partition_search(struct ldb_module *module, struct ldb_request *req)
                        talloc_free(ac);
                        return ldb_next_request(module, req);
                }
-               
-               return LDB_SUCCESS;
+
+               /* fire the first one */
+               return partition_call_first(ac);
+
        } else {
                /* Handle this like all other requests */
                if (search_control && (search_options->search_options & ~LDB_SEARCH_OPTION_PHANTOM_ROOT) == 0) {
@@ -429,14 +589,13 @@ static int partition_delete(struct ldb_module *module, struct ldb_request *req)
 /* rename */
 static int partition_rename(struct ldb_module *module, struct ldb_request *req)
 {
-       int i, matched = -1;
        /* Find backend */
        struct dsdb_control_current_partition *backend, *backend2;
        
        struct partition_private_data *data = talloc_get_type(module->private_data, 
                                                              struct partition_private_data);
 
-       /* Skip the lot if 'data' isn't here yet (initialistion) */
+       /* Skip the lot if 'data' isn't here yet (initialization) */
        if (!data) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
@@ -459,22 +618,6 @@ static int partition_rename(struct ldb_module *module, struct ldb_request *req)
                return LDB_ERR_AFFECTS_MULTIPLE_DSAS;
        }
 
-       for (i=0; data && data->partitions && data->partitions[i]; i++) {
-               if (ldb_dn_compare_base(req->op.rename.olddn, data->partitions[i]->dn) == 0) {
-                       matched = i;
-               }
-       }
-
-       if (matched > 0) {
-               ldb_asprintf_errstring(module->ldb, 
-                                      "Cannot rename from %s to %s, subtree rename would cross partition %s: %s",
-                                      ldb_dn_get_linearized(req->op.rename.olddn),
-                                      ldb_dn_get_linearized(req->op.rename.newdn),
-                                      ldb_dn_get_linearized(data->partitions[matched]->dn),
-                                      ldb_strerror(LDB_ERR_AFFECTS_MULTIPLE_DSAS));
-               return LDB_ERR_AFFECTS_MULTIPLE_DSAS;
-       }
-
        return partition_replicate(module, req, req->op.rename.olddn);
 }
 
@@ -486,24 +629,26 @@ static int partition_start_trans(struct ldb_module *module)
                                                              struct partition_private_data);
        /* Look at base DN */
        /* Figure out which partition it is under */
-       /* Skip the lot if 'data' isn't here yet (initialistion) */
+       /* Skip the lot if 'data' isn't here yet (initialization) */
        ret = ldb_next_start_trans(module);
        if (ret != LDB_SUCCESS) {
                return ret;
        }
 
        for (i=0; data && data->partitions && data->partitions[i]; i++) {
-               struct ldb_module *next = make_module_for_next_request(module, module->ldb, data->partitions[i]->module);
+               struct ldb_module *next = data->partitions[i]->module;
+               PARTITION_FIND_OP(next, start_transaction);
 
-               ret = ldb_next_start_trans(next);
-               talloc_free(next);
+               ret = next->ops->start_transaction(next);
                if (ret != LDB_SUCCESS) {
                        /* Back it out, if it fails on one */
                        for (i--; i >= 0; i--) {
-                               next = make_module_for_next_request(module, module->ldb, data->partitions[i]->module);
-                               ldb_next_del_trans(next);
-                               talloc_free(next);
+                               next = data->partitions[i]->module;
+                               PARTITION_FIND_OP(next, del_transaction);
+
+                               next->ops->del_transaction(next);
                        }
+                       ldb_next_del_trans(module);
                        return ret;
                }
        }
@@ -513,7 +658,7 @@ static int partition_start_trans(struct ldb_module *module)
 /* end a transaction */
 static int partition_end_trans(struct ldb_module *module)
 {
-       int i, ret, ret2 = LDB_SUCCESS;
+       int i, ret;
        struct partition_private_data *data = talloc_get_type(module->private_data, 
                                                              struct partition_private_data);
        ret = ldb_next_end_trans(module);
@@ -525,24 +670,24 @@ static int partition_end_trans(struct ldb_module *module)
        /* Figure out which partition it is under */
        /* Skip the lot if 'data' isn't here yet (initialistion) */
        for (i=0; data && data->partitions && data->partitions[i]; i++) {
-               struct ldb_module *next = make_module_for_next_request(module, module->ldb, data->partitions[i]->module);
-               
-               ret = ldb_next_end_trans(next);
-               talloc_free(next);
+               struct ldb_module *next = data->partitions[i]->module;
+               PARTITION_FIND_OP(next, end_transaction);
+
+               ret = next->ops->end_transaction(next);
                if (ret != LDB_SUCCESS) {
-                       ret2 = ret;
-               }
-       }
+                       /* Back it out, if it fails on one */
+                       for (i--; i >= 0; i--) {
+                               next = data->partitions[i]->module;
+                               PARTITION_FIND_OP(next, del_transaction);
 
-       if (ret != LDB_SUCCESS) {
-               /* Back it out, if it fails on one */
-               for (i=0; data && data->partitions && data->partitions[i]; i++) {
-                       struct ldb_module *next = make_module_for_next_request(module, module->ldb, data->partitions[i]->module);
-                       ldb_next_del_trans(next);
-                       talloc_free(next);
+                               next->ops->del_transaction(next);
+                       }
+                       ldb_next_del_trans(module);
+                       return ret;
                }
        }
-       return ret;
+
+       return LDB_SUCCESS;
 }
 
 /* delete a transaction */
@@ -560,10 +705,10 @@ static int partition_del_trans(struct ldb_module *module)
        /* Figure out which partition it is under */
        /* Skip the lot if 'data' isn't here yet (initialistion) */
        for (i=0; data && data->partitions && data->partitions[i]; i++) {
-               struct ldb_module *next = make_module_for_next_request(module, module->ldb, data->partitions[i]->module);
-               
-               ret = ldb_next_del_trans(next);
-               talloc_free(next);
+               struct ldb_module *next = data->partitions[i]->module;
+               PARTITION_FIND_OP(next, del_transaction);
+
+               ret = next->ops->del_transaction(next);
                if (ret != LDB_SUCCESS) {
                        ret2 = ret;
                }
@@ -571,6 +716,9 @@ static int partition_del_trans(struct ldb_module *module)
        return ret2;
 }
 
+/* NOTE: ldb_sequence_number is still a completely SYNCHRONOUS call
+ * implemented only in ldb_rdb. It does not require ldb_wait() to be
+ * called after a request is made */
 static int partition_sequence_number(struct ldb_module *module, struct ldb_request *req)
 {
        int i, ret;
@@ -593,19 +741,29 @@ static int partition_sequence_number(struct ldb_module *module, struct ldb_reque
                        seq_number = seq_number + req->op.seq_num.seq_num;
                }
 
+               /* gross hack part1 */
+               ret = ldb_request_add_control(req,
+                                       DSDB_CONTROL_CURRENT_PARTITION_OID,
+                                       false, NULL);
+               if (ret != LDB_SUCCESS) {
+                       return ret;
+               }
+
                /* Look at base DN */
                /* Figure out which partition it is under */
                /* Skip the lot if 'data' isn't here yet (initialistion) */
                for (i=0; data && data->partitions && data->partitions[i]; i++) {
-                       struct ldb_module *next = make_module_for_next_request(req, module->ldb, data->partitions[i]->module);
-                       
-                       ret = ldb_request_add_control(req, DSDB_CONTROL_CURRENT_PARTITION_OID, false, data->partitions[i]);
-                       if (ret != LDB_SUCCESS) {
-                               return ret;
+
+                       /* gross hack part2 */
+                       int j;
+                       for (j=0; req->controls[j]; j++) {
+                               if (strcmp(req->controls[j]->oid, DSDB_CONTROL_CURRENT_PARTITION_OID) == 0) {
+                                       req->controls[j]->data = data->partitions[i];
+                                       break;
+                               }
                        }
 
-                       ret = ldb_next_request(next, req);
-                       talloc_free(next);
+                       ret = partition_request(data->partitions[i]->module, req);
                        if (ret != LDB_SUCCESS) {
                                return ret;
                        }
@@ -630,15 +788,13 @@ static int partition_sequence_number(struct ldb_module *module, struct ldb_reque
                        return ret;
                }
                timestamp = date_req->op.seq_num.seq_num;
-               
+
                /* Look at base DN */
                /* Figure out which partition it is under */
                /* Skip the lot if 'data' isn't here yet (initialistion) */
                for (i=0; data && data->partitions && data->partitions[i]; i++) {
-                       struct ldb_module *next = make_module_for_next_request(req, module->ldb, data->partitions[i]->module);
-                       
-                       ret = ldb_next_request(next, date_req);
-                       talloc_free(next);
+
+                       ret = partition_request(data->partitions[i]->module, req);
                        if (ret != LDB_SUCCESS) {
                                return ret;
                        }
@@ -651,7 +807,7 @@ static int partition_sequence_number(struct ldb_module *module, struct ldb_reque
        switch (req->op.seq_num.flags) {
        case LDB_SEQ_NEXT:
        case LDB_SEQ_HIGHEST_SEQ:
-               
+
                req->op.seq_num.flags = 0;
 
                /* Has someone above set a timebase sequence? */
@@ -705,7 +861,6 @@ static int partition_extended_schema_update_now(struct ldb_module *module, struc
        struct partition_private_data *data;
        struct ldb_dn *schema_dn;
        struct partition_context *ac;
-       struct ldb_module *backend;
        int ret;
 
        schema_dn = talloc_get_type(req->op.extended.data, struct ldb_dn);
@@ -724,30 +879,33 @@ static int partition_extended_schema_update_now(struct ldb_module *module, struc
                return ldb_next_request(module, req);
        }
 
-       ac = partition_init_handle(req, module);
+       ac = partition_init_ctx(module, req);
        if (!ac) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       backend = make_module_for_next_request(req, module->ldb, partition->module);
-       if (!backend) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       ret = ldb_request_add_control(req, DSDB_CONTROL_CURRENT_PARTITION_OID, false, partition);
+       /* we need to add a control but we never touch the original request */
+       ret = partition_prep_request(ac, partition);
        if (ret != LDB_SUCCESS) {
                return ret;
        }
 
-       return ldb_next_request(backend, req);
+       /* fire the first one */
+       return partition_call_first(ac);
 }
 
 
 /* extended */
 static int partition_extended(struct ldb_module *module, struct ldb_request *req)
 {
+       struct partition_private_data *data;
        struct partition_context *ac;
 
+       data = talloc_get_type(module->private_data, struct partition_private_data);
+       if (!data || !data->partitions) {
+               return ldb_next_request(module, req);
+       }
+
        if (strcmp(req->op.extended.oid, DSDB_EXTENDED_REPLICATED_OBJECTS_OID) == 0) {
                return partition_extended_replicated_objects(module, req);
        }
@@ -762,27 +920,23 @@ static int partition_extended(struct ldb_module *module, struct ldb_request *req
         * we need to send it to all partitions
         */
 
-       ac = partition_init_handle(req, module);
+       ac = partition_init_ctx(module, req);
        if (!ac) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
-                       
+
        return partition_send_all(module, ac, req);
 }
 
-static int sort_compare(void *void1,
-                       void *void2, void *opaque)
+static int partition_sort_compare(const void *v1, const void *v2)
 {
-       struct dsdb_control_current_partition **pp1 = 
-               (struct dsdb_control_current_partition **)void1;
-       struct dsdb_control_current_partition **pp2 = 
-               (struct dsdb_control_current_partition **)void2;
-       struct dsdb_control_current_partition *partition1 = talloc_get_type(*pp1,
-                                                           struct dsdb_control_current_partition);
-       struct dsdb_control_current_partition *partition2 = talloc_get_type(*pp2,
-                                                           struct dsdb_control_current_partition);
-
-       return ldb_dn_compare(partition1->dn, partition2->dn);
+       struct dsdb_control_current_partition *p1;
+       struct dsdb_control_current_partition *p2;
+
+       p1 = *((struct dsdb_control_current_partition **)v1);
+       p2 = *((struct dsdb_control_current_partition **)v2);
+
+       return ldb_dn_compare(p1->dn, p2->dn);
 }
 
 static int partition_init(struct ldb_module *module)
@@ -888,8 +1042,8 @@ static int partition_init(struct ldb_module *module)
        data->partitions[i] = NULL;
 
        /* sort these into order, most to least specific */
-       ldb_qsort(data->partitions, partition_attributes->num_values, sizeof(*data->partitions), 
-                 module->ldb, sort_compare);
+       qsort(data->partitions, partition_attributes->num_values,
+             sizeof(*data->partitions), partition_sort_compare);
 
        for (i=0; data->partitions[i]; i++) {
                struct ldb_request *req;
@@ -902,8 +1056,19 @@ static int partition_init(struct ldb_module *module)
                
                req->operation = LDB_REQ_REGISTER_PARTITION;
                req->op.reg_partition.dn = data->partitions[i]->dn;
+               req->callback = ldb_op_default_callback;
+
+               ldb_set_timeout(module->ldb, req, 0);
+
+               req->handle = ldb_handle_new(req, module->ldb);
+               if (req->handle == NULL) {
+                       return LDB_ERR_OPERATIONS_ERROR;
+               }
                
                ret = ldb_request(module->ldb, req);
+               if (ret == LDB_SUCCESS) {
+                       ret = ldb_wait(req->handle, LDB_WAIT_ALL);
+               }
                if (ret != LDB_SUCCESS) {
                        ldb_debug(module->ldb, LDB_DEBUG_ERROR, "partition: Unable to register partition with rootdse!\n");
                        talloc_free(mem_ctx);
@@ -921,7 +1086,7 @@ static int partition_init(struct ldb_module *module)
                        talloc_free(mem_ctx);
                        return LDB_ERR_OPERATIONS_ERROR;
                }
-               
+
                for (i=0; i < replicate_attributes->num_values; i++) {
                        data->replicate[i] = ldb_dn_from_ldb_val(data->replicate, module->ldb, &replicate_attributes->values[i]);
                        if (!ldb_dn_validate(data->replicate[i])) {
@@ -1012,74 +1177,22 @@ static int partition_init(struct ldb_module *module)
                }
        }
 
-       talloc_free(mem_ctx);
-       return ldb_next_init(module);
-}
-
-static int partition_wait_none(struct ldb_handle *handle) {
-       struct partition_context *ac;
-       int ret;
-       int i;
-    
-       if (!handle || !handle->private_data) {
+       ret = ldb_mod_register_control(module, LDB_CONTROL_DOMAIN_SCOPE_OID);
+       if (ret != LDB_SUCCESS) {
+               ldb_debug(module->ldb, LDB_DEBUG_ERROR,
+                       "partition: Unable to register control with rootdse!\n");
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       if (handle->state == LDB_ASYNC_DONE) {
-               return handle->status;
-       }
-
-       handle->state = LDB_ASYNC_PENDING;
-       handle->status = LDB_SUCCESS;
-
-       ac = talloc_get_type(handle->private_data, struct partition_context);
-
-       for (i=0; i < ac->num_requests; i++) {
-               ret = ldb_wait(ac->down_req[i]->handle, LDB_WAIT_NONE);
-               
-               if (ret != LDB_SUCCESS) {
-                       handle->status = ret;
-                       goto done;
-               }
-               if (ac->down_req[i]->handle->status != LDB_SUCCESS) {
-                       handle->status = ac->down_req[i]->handle->status;
-                       goto done;
-               }
-               
-               if (ac->down_req[i]->handle->state != LDB_ASYNC_DONE) {
-                       return LDB_SUCCESS;
-               }
-       }
-
-       ret = LDB_SUCCESS;
-
-done:
-       handle->state = LDB_ASYNC_DONE;
-       return ret;
-}
-
-
-static int partition_wait_all(struct ldb_handle *handle) {
-
-       int ret;
-
-       while (handle->state != LDB_ASYNC_DONE) {
-               ret = partition_wait_none(handle);
-               if (ret != LDB_SUCCESS) {
-                       return ret;
-               }
+       ret = ldb_mod_register_control(module, LDB_CONTROL_SEARCH_OPTIONS_OID);
+       if (ret != LDB_SUCCESS) {
+               ldb_debug(module->ldb, LDB_DEBUG_ERROR,
+                       "partition: Unable to register control with rootdse!\n");
+               return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       return handle->status;
-}
-
-static int partition_wait(struct ldb_handle *handle, enum ldb_wait_type type)
-{
-       if (type == LDB_WAIT_ALL) {
-               return partition_wait_all(handle);
-       } else {
-               return partition_wait_none(handle);
-       }
+       talloc_free(mem_ctx);
+       return ldb_next_init(module);
 }
 
 _PUBLIC_ const struct ldb_module_ops ldb_partition_module_ops = {
@@ -1095,5 +1208,4 @@ _PUBLIC_ const struct ldb_module_ops ldb_partition_module_ops = {
        .start_transaction = partition_start_trans,
        .end_transaction   = partition_end_trans,
        .del_transaction   = partition_del_trans,
-       .wait              = partition_wait
 };
index 6faef63c3d7d6813f22044b4143792150de08203..e36de3c5c408e0f2b7851ba5bc7ce720f03c4188 100644 (file)
@@ -1,7 +1,7 @@
 /* 
    ldb database module
 
-   Copyright (C) Simo Sorce  2004-2006
+   Copyright (C) Simo Sorce  2004-2008
    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005-2006
    Copyright (C) Andrew Tridgell 2004
    Copyright (C) Stefan Metzmacher 2007
 
 struct ph_context {
 
-       enum ph_type {PH_ADD, PH_MOD} type;
-       enum ph_step {PH_ADD_SEARCH_DOM, PH_ADD_DO_ADD, PH_MOD_DO_REQ, PH_MOD_SEARCH_SELF, PH_MOD_SEARCH_DOM, PH_MOD_DO_MOD} step;
-
        struct ldb_module *module;
-       struct ldb_request *orig_req;
+       struct ldb_request *req;
 
        struct ldb_request *dom_req;
        struct ldb_reply *dom_res;
 
-       struct ldb_request *down_req;
-
-       struct ldb_request *search_req;
        struct ldb_reply *search_res;
 
-       struct ldb_request *mod_req;
-
        struct dom_sid *domain_sid;
+       struct domain_data *domain;
 };
 
 struct domain_data {
@@ -1378,168 +1371,193 @@ static int setup_password_fields(struct setup_password_fields_io *io)
        return LDB_SUCCESS;
 }
 
-static struct ldb_handle *ph_init_handle(struct ldb_request *req, struct ldb_module *module, enum ph_type type)
+static struct ph_context *ph_init_context(struct ldb_module *module,
+                                         struct ldb_request *req)
 {
        struct ph_context *ac;
-       struct ldb_handle *h;
 
-       h = talloc_zero(req, struct ldb_handle);
-       if (h == NULL) {
-               ldb_set_errstring(module->ldb, "Out of Memory");
-               return NULL;
-       }
-
-       h->module = module;
-
-       ac = talloc_zero(h, struct ph_context);
+       ac = talloc_zero(req, struct ph_context);
        if (ac == NULL) {
                ldb_set_errstring(module->ldb, "Out of Memory");
-               talloc_free(h);
                return NULL;
        }
 
-       h->private_data = (void *)ac;
-
-       h->state = LDB_ASYNC_INIT;
-       h->status = LDB_SUCCESS;
-
-       ac->type = type;
        ac->module = module;
-       ac->orig_req = req;
+       ac->req = req;
 
-       return h;
+       return ac;
 }
 
-static int get_domain_data_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares)
+static int ph_op_callback(struct ldb_request *req, struct ldb_reply *ares)
 {
        struct ph_context *ac;
 
-       ac = talloc_get_type(context, struct ph_context);
+       ac = talloc_get_type(req->context, struct ph_context);
 
-       /* we are interested only in the single reply (base search) we receive here */
-       if (ares->type == LDB_REPLY_ENTRY) {
-               if (ac->dom_res != NULL) {
-                       ldb_set_errstring(ldb, "Too many results");
-                       talloc_free(ares);
-                       return LDB_ERR_OPERATIONS_ERROR;
-               }
-               ac->dom_res = talloc_steal(ac, ares);
-       } else {
-               talloc_free(ares);
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
        }
-
-       return LDB_SUCCESS;
-}
-
-static int build_domain_data_request(struct ph_context *ac)
-{
-       /* attrs[] is returned from this function in
-          ac->dom_req->op.search.attrs, so it must be static, as
-          otherwise the compiler can put it on the stack */
-       static const char * const attrs[] = { "pwdProperties", "pwdHistoryLength", NULL };
-       char *filter;
-
-       ac->dom_req = talloc_zero(ac, struct ldb_request);
-       if (ac->dom_req == NULL) {
-               ldb_debug(ac->module->ldb, LDB_DEBUG_ERROR, "Out of Memory!\n");
-               return LDB_ERR_OPERATIONS_ERROR;
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
        }
-       ac->dom_req->operation = LDB_SEARCH;
-       ac->dom_req->op.search.base = ldb_get_default_basedn(ac->module->ldb);
-       ac->dom_req->op.search.scope = LDB_SCOPE_SUBTREE;
 
-       filter = talloc_asprintf(ac->dom_req,
-                                "(&(objectSid=%s)(|(|(objectClass=domain)(objectClass=builtinDomain))(objectClass=samba4LocalDomain)))", 
-                                ldap_encode_ndr_dom_sid(ac->dom_req, ac->domain_sid));
-       if (filter == NULL) {
-               ldb_debug(ac->module->ldb, LDB_DEBUG_ERROR, "Out of Memory!\n");
-               talloc_free(ac->dom_req);
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       ac->dom_req->op.search.tree = ldb_parse_tree(ac->dom_req, filter);
-       if (ac->dom_req->op.search.tree == NULL) {
-               ldb_set_errstring(ac->module->ldb, "Invalid search filter");
-               talloc_free(ac->dom_req);
-               return LDB_ERR_OPERATIONS_ERROR;
+       if (ares->type != LDB_REPLY_DONE) {
+               talloc_free(ares);
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
        }
-       ac->dom_req->op.search.attrs = attrs;
-       ac->dom_req->controls = NULL;
-       ac->dom_req->context = ac;
-       ac->dom_req->callback = get_domain_data_callback;
-       ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->dom_req);
 
-       return LDB_SUCCESS;
+       return ldb_module_done(ac->req, ares->controls,
+                               ares->response, ares->error);
 }
 
-static struct domain_data *get_domain_data(struct ldb_module *module, void *ctx, struct ldb_reply *res)
+static int password_hash_add_do_add(struct ph_context *ac);
+static int ph_modify_callback(struct ldb_request *req, struct ldb_reply *ares);
+static int password_hash_mod_search_self(struct ph_context *ac);
+static int ph_mod_search_callback(struct ldb_request *req, struct ldb_reply *ares);
+static int password_hash_mod_do_mod(struct ph_context *ac);
+
+static int get_domain_data_callback(struct ldb_request *req,
+                                   struct ldb_reply *ares)
 {
        struct domain_data *data;
-       const char *tmp;
        struct ph_context *ac;
+       int ret;
+       char *tmp;
        char *p;
 
-       ac = talloc_get_type(ctx, struct ph_context);
+       ac = talloc_get_type(req->context, struct ph_context);
 
-       data = talloc_zero(ac, struct domain_data);
-       if (data == NULL) {
-               return NULL;
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
        }
-
-       if (res == NULL) {
-               ldb_debug(module->ldb, LDB_DEBUG_ERROR, "Could not find this user's domain: %s!\n", dom_sid_string(data, ac->domain_sid));
-               talloc_free(data);
-               return NULL;
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
        }
 
-       data->pwdProperties= samdb_result_uint(res->message, "pwdProperties", 0);
-       data->store_cleartext = data->pwdProperties & DOMAIN_PASSWORD_STORE_CLEARTEXT;
-       data->pwdHistoryLength = samdb_result_uint(res->message, "pwdHistoryLength", 0);
+       switch (ares->type) {
+       case LDB_REPLY_ENTRY:
+               if (ac->domain != NULL) {
+                       ldb_set_errstring(ac->module->ldb, "Too many results");
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
+               }
 
-       /* For a domain DN, this puts things in dotted notation */
-       /* For builtin domains, this will give details for the host,
-        * but that doesn't really matter, as it's just used for salt
-        * and kerberos principals, which don't exist here */
+               data = talloc_zero(ac, struct domain_data);
+               if (data == NULL) {
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
+               }
 
-       tmp = ldb_dn_canonical_string(ctx, res->message->dn);
-       if (!tmp) {
-               return NULL;
-       }
-       
-       /* But it puts a trailing (or just before 'builtin') / on things, so kill that */
-       p = strchr(tmp, '/');
-       if (p) {
-               p[0] = '\0';
-       }
+               data->pwdProperties = samdb_result_uint(ares->message, "pwdProperties", 0);
+               data->store_cleartext = data->pwdProperties & DOMAIN_PASSWORD_STORE_CLEARTEXT;
+               data->pwdHistoryLength = samdb_result_uint(ares->message, "pwdHistoryLength", 0);
+
+               /* For a domain DN, this puts things in dotted notation */
+               /* For builtin domains, this will give details for the host,
+                * but that doesn't really matter, as it's just used for salt
+                * and kerberos principals, which don't exist here */
+
+               tmp = ldb_dn_canonical_string(data, ares->message->dn);
+               if (!tmp) {
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
+               }
+
+               /* But it puts a trailing (or just before 'builtin') / on things, so kill that */
+               p = strchr(tmp, '/');
+               if (p) {
+                       p[0] = '\0';
+               }
 
-       if (tmp != NULL) {
                data->dns_domain = strlower_talloc(data, tmp);
                if (data->dns_domain == NULL) {
-                       ldb_debug(module->ldb, LDB_DEBUG_ERROR, "Out of memory!\n");
-                       return NULL;
+                       ldb_oom(ac->module->ldb);
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
                }
                data->realm = strupper_talloc(data, tmp);
                if (data->realm == NULL) {
-                       ldb_debug(module->ldb, LDB_DEBUG_ERROR, "Out of memory!\n");
-                       return NULL;
+                       ldb_oom(ac->module->ldb);
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
                }
+               /* FIXME: NetbIOS name is *always* the first domain component ?? -SSS */
                p = strchr(tmp, '.');
                if (p) {
                        p[0] = '\0';
                }
                data->netbios_domain = strupper_talloc(data, tmp);
                if (data->netbios_domain == NULL) {
-                       ldb_debug(module->ldb, LDB_DEBUG_ERROR, "Out of memory!\n");
-                       return NULL;
+                       ldb_oom(ac->module->ldb);
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
+               }
+
+               talloc_free(tmp);
+               ac->domain = data;
+               break;
+
+       case LDB_REPLY_DONE:
+
+               /* call the next step */
+               switch (ac->req->operation) {
+               case LDB_ADD:
+                       ret = password_hash_add_do_add(ac);
+                       break;
+
+               case LDB_MODIFY:
+                       ret = password_hash_mod_do_mod(ac);
+                       break;
+
+               default:
+                       ret = LDB_ERR_OPERATIONS_ERROR;
+                       break;
+               }
+               if (ret != LDB_SUCCESS) {
+                       return ldb_module_done(ac->req, NULL, NULL, ret);
                }
+
+       case LDB_REPLY_REFERRAL:
+               /* ignore */
+               break;
        }
 
-       return data;
+       talloc_free(ares);
+       return LDB_SUCCESS;
+}
+
+static int build_domain_data_request(struct ph_context *ac)
+{
+       /* attrs[] is returned from this function in
+          ac->dom_req->op.search.attrs, so it must be static, as
+          otherwise the compiler can put it on the stack */
+       static const char * const attrs[] = { "pwdProperties", "pwdHistoryLength", NULL };
+       char *filter;
+
+       filter = talloc_asprintf(ac,
+                               "(&(objectSid=%s)(|(|(objectClass=domain)(objectClass=builtinDomain))(objectClass=samba4LocalDomain)))",
+                                ldap_encode_ndr_dom_sid(ac, ac->domain_sid));
+       if (filter == NULL) {
+               ldb_oom(ac->module->ldb);
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       return ldb_build_search_req(&ac->dom_req, ac->module->ldb, ac,
+                                   ldb_get_default_basedn(ac->module->ldb),
+                                   LDB_SCOPE_SUBTREE,
+                                   filter, attrs,
+                                   NULL,
+                                   ac, get_domain_data_callback,
+                                   ac->req);
 }
 
 static int password_hash_add(struct ldb_module *module, struct ldb_request *req)
 {
-       struct ldb_handle *h;
        struct ph_context *ac;
        struct ldb_message_element *sambaAttr;
        struct ldb_message_element *ntAttr;
@@ -1558,7 +1576,7 @@ static int password_hash_add(struct ldb_module *module, struct ldb_request *req)
                return ldb_next_request(module, req);
        }
 
-       /* nobody must touch this fields */
+       /* nobody must touch these fields */
        if (ldb_msg_find_element(req->op.add.message, "ntPwdHistory")) {
                return LDB_ERR_UNWILLING_TO_PERFORM;
        }
@@ -1617,16 +1635,16 @@ static int password_hash_add(struct ldb_module *module, struct ldb_request *req)
                return LDB_ERR_CONSTRAINT_VIOLATION;
        }
 
-       h = ph_init_handle(req, module, PH_ADD);
-       if (!h) {
+       ac = ph_init_context(module, req);
+       if (ac == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       ac = talloc_get_type(h->private_data, struct ph_context);
 
        /* get user domain data */
        ac->domain_sid = samdb_result_sid_prefix(ac, req->op.add.message, "objectSid");
        if (ac->domain_sid == NULL) {
-               ldb_debug(module->ldb, LDB_DEBUG_ERROR, "can't handle entry with missing objectSid!\n");
+               ldb_debug(module->ldb, LDB_DEBUG_ERROR,
+                         "can't handle entry with missing objectSid!\n");
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
@@ -1635,51 +1653,33 @@ static int password_hash_add(struct ldb_module *module, struct ldb_request *req)
                return ret;
        }
 
-       ac->step = PH_ADD_SEARCH_DOM;
-
-       req->handle = h;
-
        return ldb_next_request(module, ac->dom_req);
 }
 
-static int password_hash_add_do_add(struct ldb_handle *h) {
+static int password_hash_add_do_add(struct ph_context *ac) {
 
-       struct ph_context *ac;
-       struct domain_data *domain;
+       struct ldb_request *down_req;
        struct smb_krb5_context *smb_krb5_context;
        struct ldb_message *msg;
        struct setup_password_fields_io io;
        int ret;
 
-       ac = talloc_get_type(h->private_data, struct ph_context);
-
-       domain = get_domain_data(ac->module, ac, ac->dom_res);
-       if (domain == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       ac->down_req = talloc(ac, struct ldb_request);
-       if (ac->down_req == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       *(ac->down_req) = *(ac->orig_req);
-       ac->down_req->op.add.message = msg = ldb_msg_copy_shallow(ac->down_req, ac->orig_req->op.add.message);
-       if (ac->down_req->op.add.message == NULL) {
+       msg = ldb_msg_copy_shallow(ac, ac->req->op.add.message);
+       if (msg == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
        /* Some operations below require kerberos contexts */
-       if (smb_krb5_init_context(ac->down_req, 
-                                 ldb_get_opaque(h->module->ldb, "EventContext"), 
-                                 (struct loadparm_context *)ldb_get_opaque(h->module->ldb, "loadparm"), 
+       if (smb_krb5_init_context(ac,
+                                 ldb_get_event_context(ac->module->ldb),
+                                 (struct loadparm_context *)ldb_get_opaque(ac->module->ldb, "loadparm"),
                                  &smb_krb5_context) != 0) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
        ZERO_STRUCT(io);
        io.ac                           = ac;
-       io.domain                       = domain;
+       io.domain                       = ac->domain;
        io.smb_krb5_context             = smb_krb5_context;
 
        io.u.user_account_control       = samdb_result_uint(msg, "userAccountControl", 0);
@@ -1756,27 +1756,27 @@ static int password_hash_add_do_add(struct ldb_handle *h) {
                return ret;
        }
 
-       h->state = LDB_ASYNC_INIT;
-       h->status = LDB_SUCCESS;
-
-       ac->step = PH_ADD_DO_ADD;
-
-       ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->down_req);
+       ret = ldb_build_add_req(&down_req, ac->module->ldb, ac,
+                               msg,
+                               ac->req->controls,
+                               ac, ph_op_callback,
+                               ac->req);
+       if (ret != LDB_SUCCESS) {
+               return ret;
+       }
 
-       /* perform the operation */
-       return ldb_next_request(ac->module, ac->down_req);
+       return ldb_next_request(ac->module, down_req);
 }
 
-static int password_hash_mod_search_self(struct ldb_handle *h);
-
 static int password_hash_modify(struct ldb_module *module, struct ldb_request *req)
 {
-       struct ldb_handle *h;
        struct ph_context *ac;
        struct ldb_message_element *sambaAttr;
        struct ldb_message_element *ntAttr;
        struct ldb_message_element *lmAttr;
        struct ldb_message *msg;
+       struct ldb_request *down_req;
+       int ret;
 
        ldb_debug(module->ldb, LDB_DEBUG_TRACE, "password_hash_modify\n");
 
@@ -1824,83 +1824,143 @@ static int password_hash_modify(struct ldb_module *module, struct ldb_request *r
                return LDB_ERR_CONSTRAINT_VIOLATION;
        }
 
-       h = ph_init_handle(req, module, PH_MOD);
-       if (!h) {
+       ac = ph_init_context(module, req);
+       if (!ac) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       ac = talloc_get_type(h->private_data, struct ph_context);
 
-       /* return or own handle to deal with this call */
-       req->handle = h;
-
-       /* prepare the first operation */
-       ac->down_req = talloc_zero(ac, struct ldb_request);
-       if (ac->down_req == NULL) {
-               ldb_set_errstring(module->ldb, "Out of memory!");
+       /* use a new message structure so that we can modify it */
+       msg = ldb_msg_copy_shallow(ac, req->op.mod.message);
+       if (msg == NULL) {
+               ldb_oom(module->ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       *(ac->down_req) = *req; /* copy the request */
-
-       /* use a new message structure so that we can modify it */
-       ac->down_req->op.mod.message = msg = ldb_msg_copy_shallow(ac->down_req, req->op.mod.message);
-
-       /* - remove any imodification to the password from the first commit
+       /* - remove any modification to the password from the first commit
         *   we will make the real modification later */
        if (sambaAttr) ldb_msg_remove_attr(msg, "userPassword");
        if (ntAttr) ldb_msg_remove_attr(msg, "unicodePwd");
        if (lmAttr) ldb_msg_remove_attr(msg, "dBCSPwd");
 
-       /* if there was nothing else to be modify skip to next step */
+       /* if there was nothing else to be modified skip to next step */
        if (msg->num_elements == 0) {
-               talloc_free(ac->down_req);
-               ac->down_req = NULL;
-               return password_hash_mod_search_self(h);
+               return password_hash_mod_search_self(ac);
        }
-       
-       ac->down_req->context = NULL;
-       ac->down_req->callback = NULL;
 
-       ac->step = PH_MOD_DO_REQ;
+       ret = ldb_build_mod_req(&down_req, module->ldb, ac,
+                               msg,
+                               req->controls,
+                               ac, ph_modify_callback,
+                               req);
+       if (ret != LDB_SUCCESS) {
+               return ret;
+       }
 
-       ldb_set_timeout_from_prev_req(module->ldb, req, ac->down_req);
+       return ldb_next_request(module, down_req);
+}
 
-       return ldb_next_request(module, ac->down_req);
+static int ph_modify_callback(struct ldb_request *req, struct ldb_reply *ares)
+{
+       struct ph_context *ac;
+       int ret;
+
+       ac = talloc_get_type(req->context, struct ph_context);
+
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
+
+       if (ares->type != LDB_REPLY_DONE) {
+               talloc_free(ares);
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+
+       ret = password_hash_mod_search_self(ac);
+       if (ret != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, NULL, NULL, ret);
+       }
+
+       talloc_free(ares);
+       return LDB_SUCCESS;
 }
 
-static int get_self_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares)
+static int ph_mod_search_callback(struct ldb_request *req, struct ldb_reply *ares)
 {
        struct ph_context *ac;
+       int ret;
+
+       ac = talloc_get_type(req->context, struct ph_context);
 
-       ac = talloc_get_type(context, struct ph_context);
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
+
+       /* we are interested only in the single reply (base search) */
+       switch (ares->type) {
+       case LDB_REPLY_ENTRY:
 
-       /* we are interested only in the single reply (base search) we receive here */
-       if (ares->type == LDB_REPLY_ENTRY) {
                if (ac->search_res != NULL) {
-                       ldb_set_errstring(ldb, "Too many results");
+                       ldb_set_errstring(ac->module->ldb, "Too many results");
                        talloc_free(ares);
-                       return LDB_ERR_OPERATIONS_ERROR;
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
                }
 
                /* if it is not an entry of type person this is an error */
-               /* TODO: remove this when userPassword will be in schema */
+               /* TODO: remove this when sambaPassword will be in schema */
                if (!ldb_msg_check_string_attribute(ares->message, "objectClass", "person")) {
-                       ldb_set_errstring(ldb, "Object class violation");
+                       ldb_set_errstring(ac->module->ldb, "Object class violation");
                        talloc_free(ares);
-                       return LDB_ERR_OBJECT_CLASS_VIOLATION;
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OBJECT_CLASS_VIOLATION);
                }
 
                ac->search_res = talloc_steal(ac, ares);
-       } else {
-               talloc_free(ares);
+               return LDB_SUCCESS;
+
+       case LDB_REPLY_DONE:
+
+               /* get object domain sid */
+               ac->domain_sid = samdb_result_sid_prefix(ac,
+                                                       ac->search_res->message,
+                                                       "objectSid");
+               if (ac->domain_sid == NULL) {
+                       ldb_debug(ac->module->ldb, LDB_DEBUG_ERROR,
+                                 "can't handle entry without objectSid!\n");
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
+               }
+
+               /* get user domain data */
+               ret = build_domain_data_request(ac);
+               if (ret != LDB_SUCCESS) {
+                       return ldb_module_done(ac->req, NULL, NULL,ret);
+               }
+
+               return ldb_next_request(ac->module, ac->dom_req);
+
+       case LDB_REPLY_REFERRAL:
+               /*ignore anything else for now */
+               break;
        }
 
+       talloc_free(ares);
        return LDB_SUCCESS;
 }
 
-static int password_hash_mod_search_self(struct ldb_handle *h) {
+static int password_hash_mod_search_self(struct ph_context *ac) {
 
-       struct ph_context *ac;
        static const char * const attrs[] = { "userAccountControl", "lmPwdHistory", 
                                              "ntPwdHistory", 
                                              "objectSid", "msDS-KeyVersionNumber", 
@@ -1909,64 +1969,28 @@ static int password_hash_mod_search_self(struct ldb_handle *h) {
                                              "dBCSPwd", "unicodePwd",
                                              "supplementalCredentials",
                                              NULL };
-
-       ac = talloc_get_type(h->private_data, struct ph_context);
-
-       /* prepare the search operation */
-       ac->search_req = talloc_zero(ac, struct ldb_request);
-       if (ac->search_req == NULL) {
-               ldb_debug(ac->module->ldb, LDB_DEBUG_ERROR, "Out of Memory!\n");
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       ac->search_req->operation = LDB_SEARCH;
-       ac->search_req->op.search.base = ac->orig_req->op.mod.message->dn;
-       ac->search_req->op.search.scope = LDB_SCOPE_BASE;
-       ac->search_req->op.search.tree = ldb_parse_tree(ac->search_req, NULL);
-       if (ac->search_req->op.search.tree == NULL) {
-               ldb_set_errstring(ac->module->ldb, "Invalid search filter");
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-       ac->search_req->op.search.attrs = attrs;
-       ac->search_req->controls = NULL;
-       ac->search_req->context = ac;
-       ac->search_req->callback = get_self_callback;
-       ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->search_req);
-
-       ac->step = PH_MOD_SEARCH_SELF;
-
-       return ldb_next_request(ac->module, ac->search_req);
-}
-
-static int password_hash_mod_search_dom(struct ldb_handle *h) {
-
-       struct ph_context *ac;
+       struct ldb_request *search_req;
        int ret;
 
-       ac = talloc_get_type(h->private_data, struct ph_context);
+       ret = ldb_build_search_req(&search_req, ac->module->ldb, ac,
+                                  ac->req->op.mod.message->dn,
+                                  LDB_SCOPE_BASE,
+                                  "(objectclass=*)",
+                                  attrs,
+                                  NULL,
+                                  ac, ph_mod_search_callback,
+                                  ac->req);
 
-       /* get object domain sid */
-       ac->domain_sid = samdb_result_sid_prefix(ac, ac->search_res->message, "objectSid");
-       if (ac->domain_sid == NULL) {
-               ldb_debug(ac->module->ldb, LDB_DEBUG_ERROR, "can't handle entry with missing objectSid!\n");
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       /* get user domain data */
-       ret = build_domain_data_request(ac);
        if (ret != LDB_SUCCESS) {
                return ret;
        }
 
-       ac->step = PH_MOD_SEARCH_DOM;
-
-       return ldb_next_request(ac->module, ac->dom_req);
+       return ldb_next_request(ac->module, search_req);
 }
 
-static int password_hash_mod_do_mod(struct ldb_handle *h) {
+static int password_hash_mod_do_mod(struct ph_context *ac) {
 
-       struct ph_context *ac;
-       struct domain_data *domain;
+       struct ldb_request *mod_req;
        struct smb_krb5_context *smb_krb5_context;
        struct ldb_message *msg;
        struct ldb_message *orig_msg;
@@ -1974,43 +1998,29 @@ static int password_hash_mod_do_mod(struct ldb_handle *h) {
        struct setup_password_fields_io io;
        int ret;
 
-       ac = talloc_get_type(h->private_data, struct ph_context);
-
-       domain = get_domain_data(ac->module, ac, ac->dom_res);
-       if (domain == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       ac->mod_req = talloc(ac, struct ldb_request);
-       if (ac->mod_req == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       *(ac->mod_req) = *(ac->orig_req);
-       
        /* use a new message structure so that we can modify it */
-       ac->mod_req->op.mod.message = msg = ldb_msg_new(ac->mod_req);
+       msg = ldb_msg_new(ac);
        if (msg == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
        /* modify dn */
-       msg->dn = ac->orig_req->op.mod.message->dn;
+       msg->dn = ac->req->op.mod.message->dn;
 
        /* Some operations below require kerberos contexts */
-       if (smb_krb5_init_context(ac->mod_req, 
-                                 ldb_get_opaque(h->module->ldb, "EventContext"), 
-                                 (struct loadparm_context *)ldb_get_opaque(h->module->ldb, "loadparm"), 
+       if (smb_krb5_init_context(ac,
+                                 ldb_get_event_context(ac->module->ldb),
+                                 (struct loadparm_context *)ldb_get_opaque(ac->module->ldb, "loadparm"),
                                  &smb_krb5_context) != 0) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       orig_msg        = discard_const(ac->orig_req->op.mod.message);
+       orig_msg        = discard_const(ac->req->op.mod.message);
        searched_msg    = ac->search_res->message;
 
        ZERO_STRUCT(io);
        io.ac                           = ac;
-       io.domain                       = domain;
+       io.domain                       = ac->domain;
        io.smb_krb5_context             = smb_krb5_context;
 
        io.u.user_account_control       = samdb_result_uint(searched_msg, "userAccountControl", 0);
@@ -2093,189 +2103,20 @@ static int password_hash_mod_do_mod(struct ldb_handle *h) {
                return ret;
        }
 
-       h->state = LDB_ASYNC_INIT;
-       h->status = LDB_SUCCESS;
-
-       ac->step = PH_MOD_DO_MOD;
-
-       ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->mod_req);
-
-       /* perform the search */
-       return ldb_next_request(ac->module, ac->mod_req);
-}
-
-static int ph_wait(struct ldb_handle *handle) {
-       struct ph_context *ac;
-       int ret;
-    
-       if (!handle || !handle->private_data) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       if (handle->state == LDB_ASYNC_DONE) {
-               return handle->status;
-       }
-
-       handle->state = LDB_ASYNC_PENDING;
-       handle->status = LDB_SUCCESS;
-
-       ac = talloc_get_type(handle->private_data, struct ph_context);
-
-       switch (ac->step) {
-       case PH_ADD_SEARCH_DOM:
-               ret = ldb_wait(ac->dom_req->handle, LDB_WAIT_NONE);
-
-               if (ret != LDB_SUCCESS) {
-                       handle->status = ret;
-                       goto done;
-               }
-               if (ac->dom_req->handle->status != LDB_SUCCESS) {
-                       handle->status = ac->dom_req->handle->status;
-                       goto done;
-               }
-
-               if (ac->dom_req->handle->state != LDB_ASYNC_DONE) {
-                       return LDB_SUCCESS;
-               }
-
-               /* domain search done, go on */
-               return password_hash_add_do_add(handle);
-
-       case PH_ADD_DO_ADD:
-               ret = ldb_wait(ac->down_req->handle, LDB_WAIT_NONE);
-
-               if (ret != LDB_SUCCESS) {
-                       handle->status = ret;
-                       goto done;
-               }
-               if (ac->down_req->handle->status != LDB_SUCCESS) {
-                       handle->status = ac->down_req->handle->status;
-                       goto done;
-               }
-
-               if (ac->down_req->handle->state != LDB_ASYNC_DONE) {
-                       return LDB_SUCCESS;
-               }
-
-               break;
-               
-       case PH_MOD_DO_REQ:
-               ret = ldb_wait(ac->down_req->handle, LDB_WAIT_NONE);
-
-               if (ret != LDB_SUCCESS) {
-                       handle->status = ret;
-                       goto done;
-               }
-               if (ac->down_req->handle->status != LDB_SUCCESS) {
-                       handle->status = ac->down_req->handle->status;
-                       goto done;
-               }
-
-               if (ac->down_req->handle->state != LDB_ASYNC_DONE) {
-                       return LDB_SUCCESS;
-               }
-
-               /* non-password mods done, go on */
-               return password_hash_mod_search_self(handle);
-               
-       case PH_MOD_SEARCH_SELF:
-               ret = ldb_wait(ac->search_req->handle, LDB_WAIT_NONE);
-
-               if (ret != LDB_SUCCESS) {
-                       handle->status = ret;
-                       goto done;
-               }
-               if (ac->search_req->handle->status != LDB_SUCCESS) {
-                       handle->status = ac->search_req->handle->status;
-                       goto done;
-               }
-
-               if (ac->search_req->handle->state != LDB_ASYNC_DONE) {
-                       return LDB_SUCCESS;
-               }
-
-               if (ac->search_res == NULL) {
-                       return LDB_ERR_NO_SUCH_OBJECT;
-               }
-
-               /* self search done, go on */
-               return password_hash_mod_search_dom(handle);
-               
-       case PH_MOD_SEARCH_DOM:
-               ret = ldb_wait(ac->dom_req->handle, LDB_WAIT_NONE);
-
-               if (ret != LDB_SUCCESS) {
-                       handle->status = ret;
-                       goto done;
-               }
-               if (ac->dom_req->handle->status != LDB_SUCCESS) {
-                       handle->status = ac->dom_req->handle->status;
-                       goto done;
-               }
-
-               if (ac->dom_req->handle->state != LDB_ASYNC_DONE) {
-                       return LDB_SUCCESS;
-               }
-
-               /* domain search done, go on */
-               return password_hash_mod_do_mod(handle);
-
-       case PH_MOD_DO_MOD:
-               ret = ldb_wait(ac->mod_req->handle, LDB_WAIT_NONE);
-
-               if (ret != LDB_SUCCESS) {
-                       handle->status = ret;
-                       goto done;
-               }
-               if (ac->mod_req->handle->status != LDB_SUCCESS) {
-                       handle->status = ac->mod_req->handle->status;
-                       goto done;
-               }
-
-               if (ac->mod_req->handle->state != LDB_ASYNC_DONE) {
-                       return LDB_SUCCESS;
-               }
-
-               break;
-               
-       default:
-               ret = LDB_ERR_OPERATIONS_ERROR;
-               goto done;
-       }
-
-       ret = LDB_SUCCESS;
-
-done:
-       handle->state = LDB_ASYNC_DONE;
-       return ret;
-}
-
-static int ph_wait_all(struct ldb_handle *handle) {
-
-       int ret;
-
-       while (handle->state != LDB_ASYNC_DONE) {
-               ret = ph_wait(handle);
-               if (ret != LDB_SUCCESS) {
-                       return ret;
-               }
+       ret = ldb_build_mod_req(&mod_req, ac->module->ldb, ac,
+                               msg,
+                               ac->req->controls,
+                               ac, ph_op_callback,
+                               ac->req);
+       if (ret != LDB_SUCCESS) {
+               return ret;
        }
 
-       return handle->status;
-}
-
-static int password_hash_wait(struct ldb_handle *handle, enum ldb_wait_type type)
-{
-       if (type == LDB_WAIT_ALL) {
-               return ph_wait_all(handle);
-       } else {
-               return ph_wait(handle);
-       }
+       return ldb_next_request(ac->module, mod_req);
 }
 
 _PUBLIC_ const struct ldb_module_ops ldb_password_hash_module_ops = {
        .name          = "password_hash",
        .add           = password_hash_add,
        .modify        = password_hash_modify,
-       .wait          = password_hash_wait
 };
index d0a315e45a444d59359b157cdc16a0e331224f34..18b0649dda90a35d0fec7331a3302469b61c0c17 100644 (file)
@@ -50,6 +50,14 @@ struct proxy_data {
        const char **newstr;
 };
 
+struct proxy_ctx {
+       struct ldb_module *module;
+       struct ldb_request *req;
+
+#ifdef DEBUG_PROXY
+       int count;
+#endif
+};
 
 /*
   load the @PROXYINFO record
@@ -62,7 +70,6 @@ static int load_proxy_info(struct ldb_module *module)
        int ret;
        const char *olddn, *newdn, *url, *username, *password, *oldstr, *newstr;
        struct cli_credentials *creds;
-       
 
        /* see if we have already loaded it */
        if (proxy->upstream != NULL) {
@@ -105,7 +112,7 @@ static int load_proxy_info(struct ldb_module *module)
                goto failed;
        }
 
-       proxy->upstream = ldb_init(proxy);
+       proxy->upstream = ldb_init(proxy, ldb_get_event_context(ldb));
        if (proxy->upstream == NULL) {
                ldb_oom(module->ldb);
                goto failed;
@@ -180,10 +187,10 @@ static void proxy_convert_blob(TALLOC_CTX *mem_ctx, struct ldb_val *v,
 /*
   convert a returned value
 */
-static void proxy_convert_value(struct ldb_module *module, struct ldb_message *msg, struct ldb_val *v)
+static void proxy_convert_value(struct proxy_data *proxy, struct ldb_message *msg, struct ldb_val *v)
 {
-       struct proxy_data *proxy = talloc_get_type(module->private_data, struct proxy_data);
        int i;
+
        for (i=0;proxy->oldstr[i];i++) {
                char *p = strcasestr((char *)v->data, proxy->oldstr[i]);
                if (p == NULL) continue;
@@ -195,20 +202,21 @@ static void proxy_convert_value(struct ldb_module *module, struct ldb_message *m
 /*
   convert a returned value
 */
-static struct ldb_parse_tree *proxy_convert_tree(struct ldb_module *module, 
+static struct ldb_parse_tree *proxy_convert_tree(TALLOC_CTX *mem_ctx,
+                                                struct proxy_data *proxy,
                                                 struct ldb_parse_tree *tree)
 {
-       struct proxy_data *proxy = talloc_get_type(module->private_data, struct proxy_data);
        int i;
-       char *expression = ldb_filter_from_tree(module, tree);
+       char *expression = ldb_filter_from_tree(mem_ctx, tree);
+
        for (i=0;proxy->newstr[i];i++) {
                struct ldb_val v;
                char *p = strcasestr(expression, proxy->newstr[i]);
                if (p == NULL) continue;
                v.data = (uint8_t *)expression;
                v.length = strlen(expression)+1;
-               proxy_convert_blob(module, &v, proxy->newstr[i], proxy->oldstr[i]);
-               return ldb_parse_tree(module, (const char *)v.data);
+               proxy_convert_blob(mem_ctx, &v, proxy->newstr[i], proxy->oldstr[i]);
+               return ldb_parse_tree(mem_ctx, (const char *)v.data);
        }
        return tree;
 }
@@ -218,13 +226,14 @@ static struct ldb_parse_tree *proxy_convert_tree(struct ldb_module *module,
 /*
   convert a returned record
 */
-static void proxy_convert_record(struct ldb_module *module, struct ldb_message *msg)
+static void proxy_convert_record(struct ldb_context *ldb,
+                                struct proxy_data *proxy,
+                                struct ldb_message *msg)
 {
-       struct proxy_data *proxy = talloc_get_type(module->private_data, struct proxy_data);
        int attr, v;
-       
+
        /* fix the message DN */
-       if (ldb_dn_compare_base(module->ldb, proxy->olddn, msg->dn) == 0) {
+       if (ldb_dn_compare_base(proxy->olddn, msg->dn) == 0) {
                ldb_dn_remove_base_components(msg->dn, ldb_dn_get_comp_num(proxy->olddn));
                ldb_dn_add_base(msg->dn, proxy->newdn);
        }
@@ -232,21 +241,71 @@ static void proxy_convert_record(struct ldb_module *module, struct ldb_message *
        /* fix any attributes */
        for (attr=0;attr<msg->num_elements;attr++) {
                for (v=0;v<msg->elements[attr].num_values;v++) {
-                       proxy_convert_value(module, msg, &msg->elements[attr].values[v]);
+                       proxy_convert_value(proxy, msg, &msg->elements[attr].values[v]);
                }
        }
 
        /* fix any DN components */
        for (attr=0;attr<msg->num_elements;attr++) {
                for (v=0;v<msg->elements[attr].num_values;v++) {
-                       proxy_convert_value(module, msg, &msg->elements[attr].values[v]);
+                       proxy_convert_value(proxy, msg, &msg->elements[attr].values[v]);
                }
        }
 }
 
+static int proxy_search_callback(struct ldb_request *req,
+                                 struct ldb_reply *ares)
+{
+       struct proxy_data *proxy;
+       struct proxy_ctx *ac;
+       int ret;
+
+       ac = talloc_get_type(req->context, struct proxy_ctx);
+       proxy = talloc_get_type(ac->module->private_data, struct proxy_data);
+
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
+
+       /* Only entries are interesting, and we only want the olddn */
+       switch (ares->type) {
+       case LDB_REPLY_ENTRY:
+
+#ifdef DEBUG_PROXY
+               ac->count++;
+#endif
+               proxy_convert_record(ac->module->ldb, proxy, ares->message);
+               ret = ldb_module_send_entry(ac->req, ares->message);
+               break;
+
+       case LDB_REPLY_REFERRAL:
+
+               /* ignore remote referrals */
+               break;
+
+       case LDB_REPLY_DONE:
+
+#ifdef DEBUG_PROXY
+               printf("# record %d\n", ac->count+1);
+#endif
+
+               return ldb_module_done(ac->req, NULL, NULL, LDB_SUCCESS);
+       }
+
+       talloc_free(ares);
+       return ret;
+}
+
 /* search */
 static int proxy_search_bytree(struct ldb_module *module, struct ldb_request *req)
 {
+       struct proxy_ctx *ac;
+       struct ldb_parse_tree *newtree;
        struct proxy_data *proxy = talloc_get_type(module->private_data, struct proxy_data);
        struct ldb_request *newreq;
        struct ldb_dn *base;
@@ -259,55 +318,58 @@ static int proxy_search_bytree(struct ldb_module *module, struct ldb_request *re
        }
 
        if (load_proxy_info(module) != 0) {
-               return -1;
+               return LDB_ERR_OPERATIONS_ERROR;
        }
 
        /* see if the dn is within olddn */
-       if (ldb_dn_compare_base(module->ldb, proxy->newdn, req->op.search.base) != 0) {
+       if (ldb_dn_compare_base(proxy->newdn, req->op.search.base) != 0) {
                goto passthru;
        }
 
-       newreq = talloc(module, struct ldb_request);
-       if (newreq == NULL) {
-               return -1;
+       ac = talloc(req, struct proxy_ctx);
+       if (ac == NULL) {
+               return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       newreq->op.search.tree = proxy_convert_tree(module, req->op.search.tree);
+       ac->module = module;
+       ac->req = req;
+#ifdef DEBUG_PROXY
+       ac->count = 0;
+#endif
+
+       newtree = proxy_convert_tree(ac, proxy, req->op.search.tree);
 
        /* convert the basedn of this search */
-       base = ldb_dn_copy(proxy, req->op.search.base);
+       base = ldb_dn_copy(ac, req->op.search.base);
        if (base == NULL) {
-               talloc_free(newreq);
                goto failed;
        }
        ldb_dn_remove_base_components(base, ldb_dn_get_comp_num(proxy->newdn));
        ldb_dn_add_base(base, proxy->olddn);
 
        ldb_debug(module->ldb, LDB_DEBUG_FATAL, "proxying: '%s' with dn '%s' \n", 
-                 ldb_filter_from_tree(proxy, newreq->op.search.tree), ldb_dn_get_linearized(newreq->op.search.base));
+                 ldb_filter_from_tree(ac, newreq->op.search.tree), ldb_dn_get_linearized(newreq->op.search.base));
        for (i = 0; req->op.search.attrs && req->op.search.attrs[i]; i++) {
                ldb_debug(module->ldb, LDB_DEBUG_FATAL, "attr: '%s'\n", req->op.search.attrs[i]);
        }
 
-       newreq->op.search.base = base;
-       newreq->op.search.scope = req->op.search.scope;
-       newreq->op.search.attrs = req->op.search.attrs;
-       newreq->op.search.res = req->op.search.res;
-       newreq->controls = req->controls;
+       ret = ldb_build_search_req_ex(&newreq, module->ldb, ac,
+                                     base, req->op.search.scope,
+                                     newtree, req->op.search.attrs,
+                                     req->controls,
+                                     ac, proxy_search_callback,
+                                     req);
+
+       /* FIXME: warning, need a real event system hooked up for this to work properly,
+        *        for now this makes the module *not* ASYNC */
        ret = ldb_request(proxy->upstream, newreq);
        if (ret != LDB_SUCCESS) {
                ldb_set_errstring(module->ldb, ldb_errstring(proxy->upstream));
-               talloc_free(newreq);
-               return -1;
        }
-
-       for (i = 0; i < newreq->op.search.res->count; i++) {
-               printf("# record %d\n", i+1);
-               
-               proxy_convert_record(module, newreq->op.search.res->msgs[i]);
+       ret = ldb_wait(newreq->handle, LDB_WAIT_ALL);
+       if (ret != LDB_SUCCESS) {
+               ldb_set_errstring(module->ldb, ldb_errstring(proxy->upstream));
        }
-
-       talloc_free(newreq);
        return ret;
 
 failed:
index c6ebea1044e8ecd5597837e38a85ecdafd5cd012..b8e43a7e886000bcb8fc4922fc9d6736a2d649d3 100644 (file)
 #include "ldb_includes.h"
 
 struct rr_context {
-       struct ldb_request *orig_req;
-       struct ldb_request *down_req;
+       struct ldb_module *module;
+       struct ldb_request *req;
 };
 
-static int rr_search_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares) 
+static struct rr_context *rr_init_context(struct ldb_module *module,
+                                         struct ldb_request *req)
 {
-       struct rr_context *rr_context = talloc_get_type(context, struct rr_context);
-       struct ldb_request *orig_req = rr_context->orig_req;
+       struct rr_context *ac;
+
+       ac = talloc_zero(req, struct rr_context);
+       if (ac == NULL) {
+               ldb_set_errstring(module->ldb, "Out of Memory");
+               return NULL;
+       }
+
+       ac->module = module;
+       ac->req = req;
+
+       return ac;
+}
+
+static int rr_search_callback(struct ldb_request *req, struct ldb_reply *ares)
+{
+       struct rr_context *ac;
        int i, j;
-       
-       if (ares->type != LDB_REPLY_ENTRY) {
-               return rr_context->orig_req->callback(ldb, rr_context->orig_req->context, ares);
+
+       ac = talloc_get_type(req->context, struct rr_context);
+
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
+
+       if (ares->type == LDB_REPLY_REFERRAL) {
+               return ldb_module_send_referral(ac->req, ares->referral);
        }
 
+       if (ares->type == LDB_REPLY_DONE) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
+
+       /* LDB_REPLY_ENTRY */
+
        /* Find those that are range requests from the attribute list */
-       for (i = 0; orig_req->op.search.attrs[i]; i++) {
+       for (i = 0; ac->req->op.search.attrs[i]; i++) {
                char *p, *new_attr;
                const char *end_str;
                unsigned int start, end, orig_num_values;
                struct ldb_message_element *el;
                struct ldb_val *orig_values;
-               p = strchr(orig_req->op.search.attrs[i], ';');
+               p = strchr(ac->req->op.search.attrs[i], ';');
                if (!p) {
                        continue;
                }
                if (strncasecmp(p, ";range=", strlen(";range=")) != 0) {
                        continue;
                }
-               if (sscanf(p, ";range=%u-%u", &start, &end) == 2) {
-               } else if (sscanf(p, ";range=%u-*", &start) == 1) {
-                       end = (unsigned int)-1;
-               } else {
-                       continue;
+               if (sscanf(p, ";range=%u-%u", &start, &end) != 2) {
+                       if (sscanf(p, ";range=%u-*", &start) == 1) {
+                               end = (unsigned int)-1;
+                       } else {
+                               continue;
+                       }
                }
-               new_attr = talloc_strndup(orig_req, 
-                                         orig_req->op.search.attrs[i],
-                                         (unsigned int)(p-orig_req->op.search.attrs[i]));
+               new_attr = talloc_strndup(ac->req,
+                                         ac->req->op.search.attrs[i],
+                                         (size_t)(p - ac->req->op.search.attrs[i]));
 
                if (!new_attr) {
-                       ldb_oom(ldb);
-                       return LDB_ERR_OPERATIONS_ERROR;
+                       ldb_oom(ac->module->ldb);
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
                }
                el = ldb_msg_find_element(ares->message, new_attr);
                talloc_free(new_attr);
                if (!el) {
                        continue;
                }
-               if (start > end) {
-                       ldb_asprintf_errstring(ldb, "range request error: start must not be greater than end");
-                       return LDB_ERR_UNWILLING_TO_PERFORM;
-               }
                if (end >= (el->num_values - 1)) {
                        /* Need to leave the requested attribute in
                         * there (so add an empty one to match) */
@@ -91,11 +123,12 @@ static int rr_search_callback(struct ldb_context *ldb, void *context, struct ldb
                } else {
                        end_str = talloc_asprintf(el, "%u", end);
                        if (!end_str) {
-                               ldb_oom(ldb);
-                               return LDB_ERR_OPERATIONS_ERROR;
+                               ldb_oom(ac->module->ldb);
+                               return ldb_module_done(ac->req, NULL, NULL,
+                                                       LDB_ERR_OPERATIONS_ERROR);
                        }
                }
-               /* If start is greater then where we noe find the end to be */
+               /* If start is greater then where we are find the end to be */
                if (start > end) {
                        el->num_values = 0;
                        el->values = NULL;
@@ -104,16 +137,19 @@ static int rr_search_callback(struct ldb_context *ldb, void *context, struct ldb
                        orig_num_values = el->num_values;
                        
                        if ((start + end < start) || (start + end < end)) {
-                               ldb_asprintf_errstring(ldb, "range request error: start or end would overflow!");
-                               return LDB_ERR_UNWILLING_TO_PERFORM;
+                               ldb_asprintf_errstring(ac->module->ldb,
+                                       "range request error: start or end would overflow!");
+                               return ldb_module_done(ac->req, NULL, NULL,
+                                                       LDB_ERR_UNWILLING_TO_PERFORM);
                        }
                        
                        el->num_values = 0;
                        
                        el->values = talloc_array(el, struct ldb_val, (end - start) + 1);
                        if (!el->values) {
-                               ldb_oom(ldb);
-                               return LDB_ERR_OPERATIONS_ERROR;
+                               ldb_oom(ac->module->ldb);
+                               return ldb_module_done(ac->req, NULL, NULL,
+                                                       LDB_ERR_OPERATIONS_ERROR);
                        }
                        for (j=start; j <= end; j++) {
                                el->values[el->num_values] = orig_values[j];
@@ -122,13 +158,13 @@ static int rr_search_callback(struct ldb_context *ldb, void *context, struct ldb
                }
                el->name = talloc_asprintf(el, "%s;range=%u-%s", el->name, start, end_str);
                if (!el->name) {
-                       ldb_oom(ldb);
-                       return LDB_ERR_OPERATIONS_ERROR;
+                       ldb_oom(ac->module->ldb);
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
                }
        }
 
-       return rr_context->orig_req->callback(ldb, rr_context->orig_req->context, ares);
-
+       return ldb_module_send_entry(ac->req, ares->message);
 }
 
 /* search */
@@ -137,8 +173,10 @@ static int rr_search(struct ldb_module *module, struct ldb_request *req)
        int i;
        unsigned int start, end;
        const char **new_attrs = NULL;
-       struct rr_context *context;
        bool found_rr = false;
+       struct ldb_request *down_req;
+       struct rr_context *ac;
+       int ret;
 
        /* Strip the range request from the attribute */
        for (i = 0; req->op.search.attrs && req->op.search.attrs[i]; i++) {
@@ -146,19 +184,21 @@ static int rr_search(struct ldb_module *module, struct ldb_request *req)
                new_attrs = talloc_realloc(req, new_attrs, const char *, i+2);
                new_attrs[i] = req->op.search.attrs[i];
                new_attrs[i+1] = NULL;
-               p = strchr(req->op.search.attrs[i], ';');
+               p = strchr(new_attrs[i], ';');
                if (!p) {
                        continue;
                }
                if (strncasecmp(p, ";range=", strlen(";range=")) != 0) {
                        continue;
                }
-               if (sscanf(p, ";range=%u-%u", &start, &end) == 2) {
-               } else if (sscanf(p, ";range=%u-*", &start) == 1) {
-                       end = (unsigned int)-1;
-               } else {
-                       ldb_asprintf_errstring(module->ldb, "range request error: range requst malformed");
-                       return LDB_ERR_UNWILLING_TO_PERFORM;
+               end = (unsigned int)-1;
+               if (sscanf(p, ";range=%u-*", &start) != 1) {
+                       if (sscanf(p, ";range=%u-%u", &start, &end) != 2) {
+                               ldb_asprintf_errstring(module->ldb,
+                                       "range request error: "
+                                       "range request malformed");
+                               return LDB_ERR_UNWILLING_TO_PERFORM;
+                       }
                }
                if (start > end) {
                        ldb_asprintf_errstring(module->ldb, "range request error: start must not be greater than end");
@@ -166,9 +206,8 @@ static int rr_search(struct ldb_module *module, struct ldb_request *req)
                }
 
                found_rr = true;
-               new_attrs[i] = talloc_strndup(new_attrs, 
-                                             req->op.search.attrs[i],
-                                             (unsigned int)(p-req->op.search.attrs[i]));
+               new_attrs[i] = talloc_strndup(new_attrs, new_attrs[i],
+                                             (size_t)(p - new_attrs[i]));
 
                if (!new_attrs[i]) {
                        ldb_oom(module->ldb);
@@ -177,27 +216,27 @@ static int rr_search(struct ldb_module *module, struct ldb_request *req)
        }
 
        if (found_rr) {
-               int ret;
-               context = talloc(req, struct rr_context);
-               context->orig_req = req;
-               context->down_req = talloc(context, struct ldb_request);
-               *context->down_req = *req;
-               
-               context->down_req->op.search.attrs = new_attrs;
-               
-               context->down_req->callback = rr_search_callback;
-               context->down_req->context = context;
-
-               ret = ldb_next_request(module, context->down_req);
-               
-               /* We don't need to implement our own 'wait' function, so pass the handle along */
-               if (ret == LDB_SUCCESS) {
-                       req->handle = context->down_req->handle;
+               ac = rr_init_context(module, req);
+               if (!ac) {
+                       return LDB_ERR_OPERATIONS_ERROR;
+               }
+
+               ret = ldb_build_search_req_ex(&down_req, module->ldb, ac,
+                                             req->op.search.base,
+                                             req->op.search.scope,
+                                             req->op.search.tree,
+                                             new_attrs,
+                                             req->controls,
+                                             ac, rr_search_callback,
+                                             req);
+               if (ret != LDB_SUCCESS) {
+                       return ret;
                }
-               return ret;
+               return ldb_next_request(module, down_req);
        }
 
        /* No change, just run the original request as if we were never here */
+       talloc_free(new_attrs);
        return ldb_next_request(module, req);
 }
 
index dd5faf837aba3b01db50879c9b7636d5b5aad177..13a979b6f808fe5a2bbd95abd7ff0efd538b3c6a 100644 (file)
@@ -1,7 +1,7 @@
 /* 
    ldb database library
 
-   Copyright (C) Simo Sorce  2004-2006
+   Copyright (C) Simo Sorce  2004-2008
    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005
    Copyright (C) Andrew Tridgell 2005
    Copyright (C) Stefan Metzmacher <metze@samba.org> 2007
 
 struct replmd_replicated_request {
        struct ldb_module *module;
-       struct ldb_handle *handle;
-       struct ldb_request *orig_req;
+       struct ldb_request *req;
 
        const struct dsdb_schema *schema;
 
        struct dsdb_extended_replicated_objects *objs;
 
+       /* the controls we pass down */
+       struct ldb_control **controls;
+
        uint32_t index_current;
 
-       struct {
-               TALLOC_CTX *mem_ctx;
-               struct ldb_request *search_req;
-               struct ldb_message *search_msg;
-               int search_ret;
-               struct ldb_request *change_req;
-               int change_ret;
-       } sub;
+       struct ldb_message *search_msg;
 };
 
-static struct replmd_replicated_request *replmd_replicated_init_handle(struct ldb_module *module,
-                                                                      struct ldb_request *req,
-                                                                      struct dsdb_extended_replicated_objects *objs)
+static struct replmd_replicated_request *replmd_ctx_init(struct ldb_module *module,
+                                         struct ldb_request *req)
 {
-       struct replmd_replicated_request *ar;
-       struct ldb_handle *h;
-       const struct dsdb_schema *schema;
-
-       schema = dsdb_get_schema(module->ldb);
-       if (!schema) {
-               ldb_debug_set(module->ldb, LDB_DEBUG_FATAL,
-                             "replmd_replicated_init_handle: no loaded schema found\n");
-               return NULL;
-       }
+       struct replmd_replicated_request *ac;
 
-       h = talloc_zero(req, struct ldb_handle);
-       if (h == NULL) {
-               ldb_set_errstring(module->ldb, "Out of Memory");
-               return NULL;
-       }
-
-       h->module       = module;
-       h->state        = LDB_ASYNC_PENDING;
-       h->status       = LDB_SUCCESS;
-
-       ar = talloc_zero(h, struct replmd_replicated_request);
-       if (ar == NULL) {
-               ldb_set_errstring(module->ldb, "Out of Memory");
-               talloc_free(h);
+       ac = talloc_zero(req, struct replmd_replicated_request);
+       if (ac == NULL) {
+               ldb_oom(module->ldb);
                return NULL;
        }
 
-       h->private_data = ar;
-
-       ar->module      = module;
-       ar->handle      = h;
-       ar->orig_req    = req;
-       ar->schema      = schema;
-       ar->objs        = objs;
-
-       req->handle = h;
-
-       return ar;
+       ac->module = module;
+       ac->req = req;
+       return ac;
 }
 
 /*
@@ -236,34 +202,37 @@ static void replmd_ldb_message_sort(struct ldb_message *msg,
                  discard_const_p(void, schema), (ldb_qsort_cmp_fn_t)replmd_ldb_message_element_attid_sort);
 }
 
-static int replmd_prepare_originating(struct ldb_module *module, struct ldb_request *req,
-                                     struct ldb_dn *dn, const char *fn_name,
-                                     int (*fn)(struct ldb_module *,
-                                               struct ldb_request *,
-                                               const struct dsdb_schema *))
+static int replmd_op_callback(struct ldb_request *req, struct ldb_reply *ares)
 {
-       const struct dsdb_schema *schema;
-       /* do not manipulate our control entries */
-       if (ldb_dn_is_special(dn)) {
-               return ldb_next_request(module, req);
+       struct replmd_replicated_request *ac;
+
+       ac = talloc_get_type(req->context, struct replmd_replicated_request);
+
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
        }
 
-       schema = dsdb_get_schema(module->ldb);
-       if (!schema) {
-               ldb_debug_set(module->ldb, LDB_DEBUG_FATAL,
-                             "%s: no dsdb_schema loaded",
-                             fn_name);
-               return LDB_ERR_CONSTRAINT_VIOLATION;
+       if (ares->type != LDB_REPLY_DONE) {
+               ldb_set_errstring(ac->module->ldb,
+                                 "invalid ldb_reply_type in callback");
+               talloc_free(ares);
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
        }
 
-       return fn(module, req, schema);
+       return ldb_module_done(ac->req, ares->controls,
+                               ares->response, LDB_SUCCESS);
 }
 
-static int replmd_add_originating(struct ldb_module *module,
-                                 struct ldb_request *req,
-                                 const struct dsdb_schema *schema)
+static int replmd_add(struct ldb_module *module, struct ldb_request *req)
 {
+       struct replmd_replicated_request *ac;
+       const struct dsdb_schema *schema;
        enum ndr_err_code ndr_err;
        struct ldb_request *down_req;
        struct ldb_message *msg;
@@ -280,11 +249,30 @@ static int replmd_add_originating(struct ldb_module *module,
        int ret;
        uint32_t i, ni=0;
 
-       ldb_debug(module->ldb, LDB_DEBUG_TRACE, "replmd_add_originating\n");
+       /* do not manipulate our control entries */
+       if (ldb_dn_is_special(req->op.add.message->dn)) {
+               return ldb_next_request(module, req);
+       }
+
+       ldb_debug(module->ldb, LDB_DEBUG_TRACE, "replmd_add\n");
+
+       schema = dsdb_get_schema(module->ldb);
+       if (!schema) {
+               ldb_debug_set(module->ldb, LDB_DEBUG_FATAL,
+                             "replmd_modify: no dsdb_schema loaded");
+               return LDB_ERR_CONSTRAINT_VIOLATION;
+       }
+
+       ac = replmd_ctx_init(module, req);
+       if (!ac) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       ac->schema = schema;
 
        if (ldb_msg_find_element(req->op.add.message, "objectGUID")) {
                ldb_debug_set(module->ldb, LDB_DEBUG_ERROR,
-                             "replmd_add_originating: it's not allowed to add an object with objectGUID\n");
+                             "replmd_add: it's not allowed to add an object with objectGUID\n");
                return LDB_ERR_UNWILLING_TO_PERFORM;
        }
 
@@ -301,22 +289,13 @@ static int replmd_add_originating(struct ldb_module *module,
        our_invocation_id = samdb_ntds_invocation_id(module->ldb);
        if (!our_invocation_id) {
                ldb_debug_set(module->ldb, LDB_DEBUG_ERROR,
-                             "replmd_add_originating: unable to find invocationId\n");
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       /* create a copy of the request */
-       down_req = talloc(req, struct ldb_request);
-       if (down_req == NULL) {
-               ldb_oom(module->ldb);
+                             "replmd_add: unable to find invocationId\n");
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       *down_req = *req;
 
        /* we have to copy the message as the caller might have it as a const */
-       down_req->op.add.message = msg = ldb_msg_copy_shallow(down_req, req->op.add.message);
+       msg = ldb_msg_copy_shallow(ac, req->op.add.message);
        if (msg == NULL) {
-               talloc_free(down_req);
                ldb_oom(module->ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
@@ -325,7 +304,6 @@ static int replmd_add_originating(struct ldb_module *module,
        unix_to_nt_time(&now, t);
        time_str = ldb_timestring(msg, t);
        if (!time_str) {
-               talloc_free(down_req);
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
@@ -343,7 +321,6 @@ static int replmd_add_originating(struct ldb_module *module,
         */
        ret = ldb_msg_add_string(msg, "whenCreated", time_str);
        if (ret != LDB_SUCCESS) {
-               talloc_free(down_req);
                ldb_oom(module->ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
@@ -356,7 +333,6 @@ static int replmd_add_originating(struct ldb_module *module,
                                               struct replPropertyMetaData1,
                                               nmd.ctr.ctr1.count);
        if (!nmd.ctr.ctr1.array) {
-               talloc_free(down_req);
                ldb_oom(module->ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
@@ -371,9 +347,8 @@ static int replmd_add_originating(struct ldb_module *module,
                sa = dsdb_attribute_by_lDAPDisplayName(schema, e->name);
                if (!sa) {
                        ldb_debug_set(module->ldb, LDB_DEBUG_ERROR,
-                                     "replmd_add_originating: attribute '%s' not defined in schema\n",
+                                     "replmd_add: attribute '%s' not defined in schema\n",
                                      e->name);
-                       talloc_free(down_req);
                        return LDB_ERR_NO_SUCH_ATTRIBUTE;
                }
 
@@ -419,7 +394,6 @@ static int replmd_add_originating(struct ldb_module *module,
                                       &nmd,
                                       (ndr_push_flags_fn_t)ndr_push_replPropertyMetaDataBlob);
        if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
-               talloc_free(down_req);
                ldb_oom(module->ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
@@ -429,31 +403,26 @@ static int replmd_add_originating(struct ldb_module *module,
         */
        ret = ldb_msg_add_value(msg, "objectGUID", &guid_value, NULL);
        if (ret != LDB_SUCCESS) {
-               talloc_free(down_req);
                ldb_oom(module->ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
        ret = ldb_msg_add_string(msg, "whenChanged", time_str);
        if (ret != LDB_SUCCESS) {
-               talloc_free(down_req);
                ldb_oom(module->ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
        ret = samdb_msg_add_uint64(module->ldb, msg, msg, "uSNCreated", seq_num);
        if (ret != LDB_SUCCESS) {
-               talloc_free(down_req);
                ldb_oom(module->ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
        ret = samdb_msg_add_uint64(module->ldb, msg, msg, "uSNChanged", seq_num);
        if (ret != LDB_SUCCESS) {
-               talloc_free(down_req);
                ldb_oom(module->ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
        ret = ldb_msg_add_value(msg, "replPropertyMetaData", &nmd_value, NULL);
        if (ret != LDB_SUCCESS) {
-               talloc_free(down_req);
                ldb_oom(module->ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
@@ -463,49 +432,54 @@ static int replmd_add_originating(struct ldb_module *module,
         */
        replmd_ldb_message_sort(msg, schema);
 
-       ldb_set_timeout_from_prev_req(module->ldb, req, down_req);
-
-       /* go on with the call chain */
-       ret = ldb_next_request(module, down_req);
-
-       /* do not free down_req as the call results may be linked to it,
-        * it will be freed when the upper level request get freed */
-       if (ret == LDB_SUCCESS) {
-               req->handle = down_req->handle;
+       ret = ldb_build_add_req(&down_req, module->ldb, ac,
+                               msg,
+                               req->controls,
+                               ac, replmd_op_callback,
+                               req);
+       if (ret != LDB_SUCCESS) {
+               return ret;
        }
 
-       return ret;
-}
-
-static int replmd_add(struct ldb_module *module, struct ldb_request *req)
-{
-       return replmd_prepare_originating(module, req, req->op.add.message->dn,
-                                         "replmd_add", replmd_add_originating);
+       /* go on with the call chain */
+       return ldb_next_request(module, down_req);
 }
 
-static int replmd_modify_originating(struct ldb_module *module,
-                                    struct ldb_request *req,
-                                    const struct dsdb_schema *schema)
+static int replmd_modify(struct ldb_module *module, struct ldb_request *req)
 {
+       struct replmd_replicated_request *ac;
+       const struct dsdb_schema *schema;
        struct ldb_request *down_req;
        struct ldb_message *msg;
        int ret;
        time_t t = time(NULL);
        uint64_t seq_num;
 
-       ldb_debug(module->ldb, LDB_DEBUG_TRACE, "replmd_modify_originating\n");
+       /* do not manipulate our control entries */
+       if (ldb_dn_is_special(req->op.mod.message->dn)) {
+               return ldb_next_request(module, req);
+       }
+
+       ldb_debug(module->ldb, LDB_DEBUG_TRACE, "replmd_modify\n");
+
+       schema = dsdb_get_schema(module->ldb);
+       if (!schema) {
+               ldb_debug_set(module->ldb, LDB_DEBUG_FATAL,
+                             "replmd_modify: no dsdb_schema loaded");
+               return LDB_ERR_CONSTRAINT_VIOLATION;
+       }
 
-       down_req = talloc(req, struct ldb_request);
-       if (down_req == NULL) {
+       ac = replmd_ctx_init(module, req);
+       if (!ac) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       *down_req = *req;
+       ac->schema = schema;
 
        /* we have to copy the message as the caller might have it as a const */
-       down_req->op.mod.message = msg = ldb_msg_copy_shallow(down_req, req->op.mod.message);
+       msg = ldb_msg_copy_shallow(ac, req->op.mod.message);
        if (msg == NULL) {
-               talloc_free(down_req);
+               talloc_free(ac);
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
@@ -522,7 +496,7 @@ static int replmd_modify_originating(struct ldb_module *module,
         */
 
        if (add_time_element(msg, "whenChanged", t) != 0) {
-               talloc_free(down_req);
+               talloc_free(ac);
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
@@ -530,7 +504,7 @@ static int replmd_modify_originating(struct ldb_module *module,
        ret = ldb_sequence_number(module->ldb, LDB_SEQ_NEXT, &seq_num);
        if (ret == LDB_SUCCESS) {
                if (add_uint64_element(msg, "uSNChanged", seq_num) != 0) {
-                       talloc_free(down_req);
+                       talloc_free(ac);
                        return LDB_ERR_OPERATIONS_ERROR;
                }
        }
@@ -540,96 +514,71 @@ static int replmd_modify_originating(struct ldb_module *module,
         * - replace the old object with the newly constructed one
         */
 
-       ldb_set_timeout_from_prev_req(module->ldb, req, down_req);
-
-       /* go on with the call chain */
-       ret = ldb_next_request(module, down_req);
-
-       /* do not free down_req as the call results may be linked to it,
-        * it will be freed when the upper level request get freed */
-       if (ret == LDB_SUCCESS) {
-               req->handle = down_req->handle;
-       }
-
-       return ret;
-}
-
-static int replmd_modify(struct ldb_module *module, struct ldb_request *req)
-{
-       return replmd_prepare_originating(module, req, req->op.mod.message->dn,
-                                         "replmd_modify", replmd_modify_originating);
-}
-
-static int replmd_replicated_request_reply_helper(struct replmd_replicated_request *ar, int ret)
-{
-       struct ldb_reply *ares = NULL;
-
-       ar->handle->status = ret;
-       ar->handle->state = LDB_ASYNC_DONE;
-
-       if (!ar->orig_req->callback) {
-               return LDB_SUCCESS;
-       }
-       
-       /* we're done and need to report the success to the caller */
-       ares = talloc_zero(ar, struct ldb_reply);
-       if (!ares) {
-               ar->handle->status = LDB_ERR_OPERATIONS_ERROR;
-               ar->handle->state = LDB_ASYNC_DONE;
-               return LDB_ERR_OPERATIONS_ERROR;
+       ret = ldb_build_mod_req(&down_req, module->ldb, ac,
+                               msg,
+                               req->controls,
+                               ac, replmd_op_callback,
+                               req);
+       if (ret != LDB_SUCCESS) {
+               return ret;
        }
+       talloc_steal(down_req, msg);
 
-       ares->type      = LDB_REPLY_EXTENDED;
-       ares->response  = NULL;
-
-       return ar->orig_req->callback(ar->module->ldb, ar->orig_req->context, ares);
-}
-
-static int replmd_replicated_request_done(struct replmd_replicated_request *ar)
-{
-       return replmd_replicated_request_reply_helper(ar, LDB_SUCCESS);
+       /* go on with the call chain */
+       return ldb_next_request(module, down_req);
 }
 
 static int replmd_replicated_request_error(struct replmd_replicated_request *ar, int ret)
 {
-       return replmd_replicated_request_reply_helper(ar, ret);
+       return ret;
 }
 
 static int replmd_replicated_request_werror(struct replmd_replicated_request *ar, WERROR status)
 {
        int ret = LDB_ERR_OTHER;
        /* TODO: do some error mapping */
-       return replmd_replicated_request_reply_helper(ar, ret);
+       return ret;
 }
 
 static int replmd_replicated_apply_next(struct replmd_replicated_request *ar);
 
-static int replmd_replicated_apply_add_callback(struct ldb_context *ldb,
-                                               void *private_data,
+static int replmd_replicated_apply_add_callback(struct ldb_request *req,
                                                struct ldb_reply *ares)
 {
-#ifdef REPLMD_FULL_ASYNC /* TODO: activate this code when ldb support full async code */ 
-       struct replmd_replicated_request *ar = talloc_get_type(private_data,
+       struct replmd_replicated_request *ar = talloc_get_type(req->context,
                                               struct replmd_replicated_request);
+       int ret;
 
-       ar->sub.change_ret = ldb_wait(ar->sub.search_req->handle, LDB_WAIT_ALL);
-       if (ar->sub.change_ret != LDB_SUCCESS) {
-               return replmd_replicated_request_error(ar, ar->sub.change_ret);
+
+       if (!ares) {
+               return ldb_module_done(ar->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ar->req, ares->controls,
+                                       ares->response, ares->error);
        }
 
-       talloc_free(ar->sub.mem_ctx);
-       ZERO_STRUCT(ar->sub);
+       if (ares->type != LDB_REPLY_DONE) {
+               ldb_set_errstring(ar->module->ldb, "Invalid reply type\n!");
+               return ldb_module_done(ar->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
 
+       talloc_free(ares);
        ar->index_current++;
 
-       return replmd_replicated_apply_next(ar);
-#else
+       ret = replmd_replicated_apply_next(ar);
+       if (ret != LDB_SUCCESS) {
+               return ldb_module_done(ar->req, NULL, NULL, ret);
+       }
+
        return LDB_SUCCESS;
-#endif
 }
 
 static int replmd_replicated_apply_add(struct replmd_replicated_request *ar)
 {
+       struct ldb_request *change_req;
        enum ndr_err_code ndr_err;
        struct ldb_message *msg;
        struct replPropertyMetaDataBlob *md;
@@ -696,39 +645,17 @@ static int replmd_replicated_apply_add(struct replmd_replicated_request *ar)
 
        replmd_ldb_message_sort(msg, ar->schema);
 
-       ret = ldb_build_add_req(&ar->sub.change_req,
+       ret = ldb_build_add_req(&change_req,
                                ar->module->ldb,
-                               ar->sub.mem_ctx,
+                               ar,
                                msg,
-                               NULL,
+                               ar->controls,
                                ar,
-                               replmd_replicated_apply_add_callback);
+                               replmd_replicated_apply_add_callback,
+                               ar->req);
        if (ret != LDB_SUCCESS) return replmd_replicated_request_error(ar, ret);
 
-#ifdef REPLMD_FULL_ASYNC /* TODO: activate this code when ldb support full async code */ 
-       return ldb_next_request(ar->module, ar->sub.change_req);
-#else
-       ret = ldb_next_request(ar->module, ar->sub.change_req);
-       if (ret != LDB_SUCCESS) {
-               ldb_asprintf_errstring(ar->module->ldb, "Failed to add replicated object %s: %s", ldb_dn_get_linearized(ar->sub.change_req->op.add.message->dn), 
-                                      ldb_errstring(ar->module->ldb));
-               return replmd_replicated_request_error(ar, ret);
-       }
-
-       ar->sub.change_ret = ldb_wait(ar->sub.change_req->handle, LDB_WAIT_ALL);
-       if (ar->sub.change_ret != LDB_SUCCESS) {
-               ldb_asprintf_errstring(ar->module->ldb, "Failed while waiting on add replicated object %s: %s", ldb_dn_get_linearized(ar->sub.change_req->op.add.message->dn), 
-                                      ldb_errstring(ar->module->ldb));
-               return replmd_replicated_request_error(ar, ar->sub.change_ret);
-       }
-
-       talloc_free(ar->sub.mem_ctx);
-       ZERO_STRUCT(ar->sub);
-
-       ar->index_current++;
-
-       return LDB_SUCCESS;
-#endif
+       return ldb_next_request(ar->module, change_req);
 }
 
 static int replmd_replPropertyMetaData1_conflict_compare(struct replPropertyMetaData1 *m1,
@@ -752,35 +679,42 @@ static int replmd_replPropertyMetaData1_conflict_compare(struct replPropertyMeta
        return m1->originating_usn - m2->originating_usn;
 }
 
-static int replmd_replicated_apply_merge_callback(struct ldb_context *ldb,
-                                                 void *private_data,
+static int replmd_replicated_apply_merge_callback(struct ldb_request *req,
                                                  struct ldb_reply *ares)
 {
-#ifdef REPLMD_FULL_ASYNC /* TODO: activate this code when ldb support full async code */ 
-       struct replmd_replicated_request *ar = talloc_get_type(private_data,
+       struct replmd_replicated_request *ar = talloc_get_type(req->context,
                                               struct replmd_replicated_request);
+       int ret;
 
-       ret = ldb_next_request(ar->module, ar->sub.change_req);
-       if (ret != LDB_SUCCESS) return replmd_replicated_request_error(ar, ret);
-
-       ar->sub.change_ret = ldb_wait(ar->sub.search_req->handle, LDB_WAIT_ALL);
-       if (ar->sub.change_ret != LDB_SUCCESS) {
-               return replmd_replicated_request_error(ar, ar->sub.change_ret);
+       if (!ares) {
+               return ldb_module_done(ar->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ar->req, ares->controls,
+                                       ares->response, ares->error);
        }
 
-       talloc_free(ar->sub.mem_ctx);
-       ZERO_STRUCT(ar->sub);
+       if (ares->type != LDB_REPLY_DONE) {
+               ldb_set_errstring(ar->module->ldb, "Invalid reply type\n!");
+               return ldb_module_done(ar->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
 
+       talloc_free(ares);
        ar->index_current++;
 
+       ret = replmd_replicated_apply_next(ar);
+       if (ret != LDB_SUCCESS) {
+               return ldb_module_done(ar->req, NULL, NULL, ret);
+       }
+
        return LDB_SUCCESS;
-#else
-       return LDB_SUCCESS;
-#endif
 }
 
 static int replmd_replicated_apply_merge(struct replmd_replicated_request *ar)
 {
+       struct ldb_request *change_req;
        enum ndr_err_code ndr_err;
        struct ldb_message *msg;
        struct replPropertyMetaDataBlob *rmd;
@@ -801,11 +735,11 @@ static int replmd_replicated_apply_merge(struct replmd_replicated_request *ar)
        /*
         * TODO: add rename conflict handling
         */
-       if (ldb_dn_compare(msg->dn, ar->sub.search_msg->dn) != 0) {
+       if (ldb_dn_compare(msg->dn, ar->search_msg->dn) != 0) {
                ldb_debug_set(ar->module->ldb, LDB_DEBUG_FATAL, "replmd_replicated_apply_merge[%u]: rename not supported",
                              ar->index_current);
                ldb_debug(ar->module->ldb, LDB_DEBUG_FATAL, "%s => %s\n",
-                         ldb_dn_get_linearized(ar->sub.search_msg->dn),
+                         ldb_dn_get_linearized(ar->search_msg->dn),
                          ldb_dn_get_linearized(msg->dn));
                return replmd_replicated_request_werror(ar, WERR_NOT_SUPPORTED);
        }
@@ -816,9 +750,9 @@ static int replmd_replicated_apply_merge(struct replmd_replicated_request *ar)
        }
 
        /* find existing meta data */
-       omd_value = ldb_msg_find_ldb_val(ar->sub.search_msg, "replPropertyMetaData");
+       omd_value = ldb_msg_find_ldb_val(ar->search_msg, "replPropertyMetaData");
        if (omd_value) {
-               ndr_err = ndr_pull_struct_blob(omd_value, ar->sub.mem_ctx, 
+               ndr_err = ndr_pull_struct_blob(omd_value, ar,
                                               lp_iconv_convenience(ldb_get_opaque(ar->module->ldb, "loadparm")), &omd,
                                               (ndr_pull_flags_fn_t)ndr_pull_replPropertyMetaDataBlob);
                if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
@@ -834,7 +768,7 @@ static int replmd_replicated_apply_merge(struct replmd_replicated_request *ar)
        ZERO_STRUCT(nmd);
        nmd.version = 1;
        nmd.ctr.ctr1.count = omd.ctr.ctr1.count + rmd->ctr.ctr1.count;
-       nmd.ctr.ctr1.array = talloc_array(ar->sub.mem_ctx,
+       nmd.ctr.ctr1.array = talloc_array(ar,
                                          struct replPropertyMetaData1,
                                          nmd.ctr.ctr1.count);
        if (!nmd.ctr.ctr1.array) return replmd_replicated_request_werror(ar, WERR_NOMEM);
@@ -917,14 +851,16 @@ static int replmd_replicated_apply_merge(struct replmd_replicated_request *ar)
        if (msg->num_elements == 0) {
                ldb_debug(ar->module->ldb, LDB_DEBUG_TRACE, "replmd_replicated_apply_merge[%u]: skip replace\n",
                          ar->index_current);
-               goto next_object;
+
+               ar->index_current++;
+               return replmd_replicated_apply_next(ar);
        }
 
        ldb_debug(ar->module->ldb, LDB_DEBUG_TRACE, "replmd_replicated_apply_merge[%u]: replace %u attributes\n",
                  ar->index_current, msg->num_elements);
 
        /*
-        * when we now that we'll modify the record, add the whenChanged, uSNChanged
+        * when we know that we'll modify the record, add the whenChanged, uSNChanged
         * and replPopertyMetaData attributes
         */
        ret = ldb_msg_add_string(msg, "whenChanged", ar->objs->objects[ar->index_current].when_changed);
@@ -947,150 +883,123 @@ static int replmd_replicated_apply_merge(struct replmd_replicated_request *ar)
                msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
        }
 
-       ret = ldb_build_mod_req(&ar->sub.change_req,
+       ret = ldb_build_mod_req(&change_req,
                                ar->module->ldb,
-                               ar->sub.mem_ctx,
+                               ar,
                                msg,
-                               NULL,
+                               ar->controls,
                                ar,
-                               replmd_replicated_apply_merge_callback);
-       if (ret != LDB_SUCCESS) return replmd_replicated_request_error(ar, ret);
-
-#ifdef REPLMD_FULL_ASYNC /* TODO: activate this code when ldb support full async code */ 
-       return ldb_next_request(ar->module, ar->sub.change_req);
-#else
-       ret = ldb_next_request(ar->module, ar->sub.change_req);
+                               replmd_replicated_apply_merge_callback,
+                               ar->req);
        if (ret != LDB_SUCCESS) return replmd_replicated_request_error(ar, ret);
 
-       ar->sub.change_ret = ldb_wait(ar->sub.change_req->handle, LDB_WAIT_ALL);
-       if (ar->sub.change_ret != LDB_SUCCESS) {
-               return replmd_replicated_request_error(ar, ar->sub.change_ret);
-       }
-
-next_object:
-       talloc_free(ar->sub.mem_ctx);
-       ZERO_STRUCT(ar->sub);
-
-       ar->index_current++;
-
-       return LDB_SUCCESS;
-#endif
+       return ldb_next_request(ar->module, change_req);
 }
 
-static int replmd_replicated_apply_search_callback(struct ldb_context *ldb,
-                                                  void *private_data,
+static int replmd_replicated_apply_search_callback(struct ldb_request *req,
                                                   struct ldb_reply *ares)
 {
-       struct replmd_replicated_request *ar = talloc_get_type(private_data,
+       struct replmd_replicated_request *ar = talloc_get_type(req->context,
                                               struct replmd_replicated_request);
-       bool is_done = false;
+       int ret;
+
+       if (!ares) {
+               return ldb_module_done(ar->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS &&
+           ares->error != LDB_ERR_NO_SUCH_OBJECT) {
+               return ldb_module_done(ar->req, ares->controls,
+                                       ares->response, ares->error);
+       }
 
        switch (ares->type) {
        case LDB_REPLY_ENTRY:
-               ar->sub.search_msg = talloc_steal(ar->sub.mem_ctx, ares->message);
+               ar->search_msg = talloc_steal(ar, ares->message);
                break;
+
        case LDB_REPLY_REFERRAL:
                /* we ignore referrals */
                break;
-       case LDB_REPLY_EXTENDED:
-       case LDB_REPLY_DONE:
-               is_done = true;
-       }
-
-       talloc_free(ares);
 
-#ifdef REPLMD_FULL_ASYNC /* TODO: activate this code when ldb support full async code */ 
-       if (is_done) {
-               ar->sub.search_ret = ldb_wait(ar->sub.search_req->handle, LDB_WAIT_ALL);
-               if (ar->sub.search_ret != LDB_SUCCESS) {
-                       return replmd_replicated_request_error(ar, ar->sub.search_ret);
+       case LDB_REPLY_DONE:
+               if (ar->search_msg != NULL) {
+                       ret = replmd_replicated_apply_merge(ar);
+               } else {
+                       ret = replmd_replicated_apply_add(ar);
                }
-               if (ar->sub.search_msg) {
-                       return replmd_replicated_apply_merge(ar);
+               if (ret != LDB_SUCCESS) {
+                       return ldb_module_done(ar->req, NULL, NULL, ret);
                }
-               return replmd_replicated_apply_add(ar);
        }
-#endif
+
+       talloc_free(ares);
        return LDB_SUCCESS;
 }
 
-static int replmd_replicated_apply_search(struct replmd_replicated_request *ar)
+static int replmd_replicated_uptodate_vector(struct replmd_replicated_request *ar);
+
+static int replmd_replicated_apply_next(struct replmd_replicated_request *ar)
 {
        int ret;
        char *tmp_str;
        char *filter;
+       struct ldb_request *search_req;
+
+       if (ar->index_current >= ar->objs->num_objects) {
+               /* done with it, go to the last op */
+               return replmd_replicated_uptodate_vector(ar);
+       }
+
+       ar->search_msg = NULL;
 
-       tmp_str = ldb_binary_encode(ar->sub.mem_ctx, ar->objs->objects[ar->index_current].guid_value);
+       tmp_str = ldb_binary_encode(ar, ar->objs->objects[ar->index_current].guid_value);
        if (!tmp_str) return replmd_replicated_request_werror(ar, WERR_NOMEM);
 
-       filter = talloc_asprintf(ar->sub.mem_ctx, "(objectGUID=%s)", tmp_str);
+       filter = talloc_asprintf(ar, "(objectGUID=%s)", tmp_str);
        if (!filter) return replmd_replicated_request_werror(ar, WERR_NOMEM);
        talloc_free(tmp_str);
 
-       ret = ldb_build_search_req(&ar->sub.search_req,
+       ret = ldb_build_search_req(&search_req,
                                   ar->module->ldb,
-                                  ar->sub.mem_ctx,
+                                  ar,
                                   ar->objs->partition_dn,
                                   LDB_SCOPE_SUBTREE,
                                   filter,
                                   NULL,
                                   NULL,
                                   ar,
-                                  replmd_replicated_apply_search_callback);
-       if (ret != LDB_SUCCESS) return replmd_replicated_request_error(ar, ret);
-
-#ifdef REPLMD_FULL_ASYNC /* TODO: activate this code when ldb support full async code */ 
-       return ldb_next_request(ar->module, ar->sub.search_req);
-#else
-       ret = ldb_next_request(ar->module, ar->sub.search_req);
+                                  replmd_replicated_apply_search_callback,
+                                  ar->req);
        if (ret != LDB_SUCCESS) return replmd_replicated_request_error(ar, ret);
 
-       ar->sub.search_ret = ldb_wait(ar->sub.search_req->handle, LDB_WAIT_ALL);
-       if (ar->sub.search_ret != LDB_SUCCESS && ar->sub.search_ret != LDB_ERR_NO_SUCH_OBJECT) {
-               return replmd_replicated_request_error(ar, ar->sub.search_ret);
-       }
-       if (ar->sub.search_msg) {
-               return replmd_replicated_apply_merge(ar);
-       }
-
-       return replmd_replicated_apply_add(ar);
-#endif
-}
-
-static int replmd_replicated_apply_next(struct replmd_replicated_request *ar)
-{
-#ifdef REPLMD_FULL_ASYNC /* TODO: activate this code when ldb support full async code */ 
-       if (ar->index_current >= ar->objs->num_objects) {
-               return replmd_replicated_uptodate_vector(ar);
-       }
-#endif
-
-       ar->sub.mem_ctx = talloc_new(ar);
-       if (!ar->sub.mem_ctx) return replmd_replicated_request_werror(ar, WERR_NOMEM);
-
-       return replmd_replicated_apply_search(ar);
+       return ldb_next_request(ar->module, search_req);
 }
 
-static int replmd_replicated_uptodate_modify_callback(struct ldb_context *ldb,
-                                                     void *private_data,
+static int replmd_replicated_uptodate_modify_callback(struct ldb_request *req,
                                                      struct ldb_reply *ares)
 {
-#ifdef REPLMD_FULL_ASYNC /* TODO: activate this code when ldb support full async code */ 
-       struct replmd_replicated_request *ar = talloc_get_type(private_data,
+       struct replmd_replicated_request *ar = talloc_get_type(req->context,
                                               struct replmd_replicated_request);
 
-       ar->sub.change_ret = ldb_wait(ar->sub.search_req->handle, LDB_WAIT_ALL);
-       if (ar->sub.change_ret != LDB_SUCCESS) {
-               return replmd_replicated_request_error(ar, ar->sub.change_ret);
+       if (!ares) {
+               return ldb_module_done(ar->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ar->req, ares->controls,
+                                       ares->response, ares->error);
        }
 
-       talloc_free(ar->sub.mem_ctx);
-       ZERO_STRUCT(ar->sub);
+       if (ares->type != LDB_REPLY_DONE) {
+               ldb_set_errstring(ar->module->ldb, "Invalid reply type\n!");
+               return ldb_module_done(ar->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
 
-       return replmd_replicated_request_done(ar);
-#else
-       return LDB_SUCCESS;
-#endif
+       talloc_free(ares);
+
+       return ldb_module_done(ar->req, NULL, NULL, LDB_SUCCESS);
 }
 
 static int replmd_drsuapi_DsReplicaCursor2_compare(const struct drsuapi_DsReplicaCursor2 *c1,
@@ -1101,6 +1010,7 @@ static int replmd_drsuapi_DsReplicaCursor2_compare(const struct drsuapi_DsReplic
 
 static int replmd_replicated_uptodate_modify(struct replmd_replicated_request *ar)
 {
+       struct ldb_request *change_req;
        enum ndr_err_code ndr_err;
        struct ldb_message *msg;
        struct replUpToDateVectorBlob ouv;
@@ -1142,9 +1052,9 @@ static int replmd_replicated_uptodate_modify(struct replmd_replicated_request *a
        /*
         * first create the new replUpToDateVector
         */
-       ouv_value = ldb_msg_find_ldb_val(ar->sub.search_msg, "replUpToDateVector");
+       ouv_value = ldb_msg_find_ldb_val(ar->search_msg, "replUpToDateVector");
        if (ouv_value) {
-               ndr_err = ndr_pull_struct_blob(ouv_value, ar->sub.mem_ctx, 
+               ndr_err = ndr_pull_struct_blob(ouv_value, ar,
                                               lp_iconv_convenience(ldb_get_opaque(ar->module->ldb, "loadparm")), &ouv,
                                               (ndr_pull_flags_fn_t)ndr_pull_replUpToDateVectorBlob);
                if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
@@ -1165,7 +1075,7 @@ static int replmd_replicated_uptodate_modify(struct replmd_replicated_request *a
         */
        nuv.ctr.ctr2.count = 1 + ouv.ctr.ctr2.count;
        if (ruv) nuv.ctr.ctr2.count += ruv->count;
-       nuv.ctr.ctr2.cursors = talloc_array(ar->sub.mem_ctx,
+       nuv.ctr.ctr2.cursors = talloc_array(ar,
                                            struct drsuapi_DsReplicaCursor2,
                                            nuv.ctr.ctr2.count);
        if (!nuv.ctr.ctr2.cursors) return replmd_replicated_request_werror(ar, WERR_NOMEM);
@@ -1266,9 +1176,9 @@ static int replmd_replicated_uptodate_modify(struct replmd_replicated_request *a
        /*
         * create the change ldb_message
         */
-       msg = ldb_msg_new(ar->sub.mem_ctx);
+       msg = ldb_msg_new(ar);
        if (!msg) return replmd_replicated_request_werror(ar, WERR_NOMEM);
-       msg->dn = ar->sub.search_msg->dn;
+       msg->dn = ar->search_msg->dn;
 
        ndr_err = ndr_push_struct_blob(&nuv_value, msg, 
                                       lp_iconv_convenience(ldb_get_opaque(ar->module->ldb, "loadparm")), 
@@ -1301,12 +1211,12 @@ static int replmd_replicated_uptodate_modify(struct replmd_replicated_request *a
         * first see if we already have a repsFrom value for the current source dsa
         * if so we'll later replace this value
         */
-       orf_el = ldb_msg_find_element(ar->sub.search_msg, "repsFrom");
+       orf_el = ldb_msg_find_element(ar->search_msg, "repsFrom");
        if (orf_el) {
                for (i=0; i < orf_el->num_values; i++) {
                        struct repsFromToBlob *trf;
 
-                       trf = talloc(ar->sub.mem_ctx, struct repsFromToBlob);
+                       trf = talloc(ar, struct repsFromToBlob);
                        if (!trf) return replmd_replicated_request_werror(ar, WERR_NOMEM);
 
                        ndr_err = ndr_pull_struct_blob(&orf_el->values[i], trf, lp_iconv_convenience(ldb_get_opaque(ar->module->ldb, "loadparm")), trf,
@@ -1375,72 +1285,62 @@ static int replmd_replicated_uptodate_modify(struct replmd_replicated_request *a
        nrf_el->flags = LDB_FLAG_MOD_REPLACE;
 
        /* prepare the ldb_modify() request */
-       ret = ldb_build_mod_req(&ar->sub.change_req,
+       ret = ldb_build_mod_req(&change_req,
                                ar->module->ldb,
-                               ar->sub.mem_ctx,
+                               ar,
                                msg,
-                               NULL,
+                               ar->controls,
                                ar,
-                               replmd_replicated_uptodate_modify_callback);
-       if (ret != LDB_SUCCESS) return replmd_replicated_request_error(ar, ret);
-
-#ifdef REPLMD_FULL_ASYNC /* TODO: activate this code when ldb support full async code */ 
-       return ldb_next_request(ar->module, ar->sub.change_req);
-#else
-       ret = ldb_next_request(ar->module, ar->sub.change_req);
+                               replmd_replicated_uptodate_modify_callback,
+                               ar->req);
        if (ret != LDB_SUCCESS) return replmd_replicated_request_error(ar, ret);
 
-       ar->sub.change_ret = ldb_wait(ar->sub.search_req->handle, LDB_WAIT_ALL);
-       if (ar->sub.change_ret != LDB_SUCCESS) {
-               return replmd_replicated_request_error(ar, ar->sub.change_ret);
-       }
-
-       talloc_free(ar->sub.mem_ctx);
-       ZERO_STRUCT(ar->sub);
-
-       return replmd_replicated_request_done(ar);
-#endif
+       return ldb_next_request(ar->module, change_req);
 }
 
-static int replmd_replicated_uptodate_search_callback(struct ldb_context *ldb,
-                                                     void *private_data,
+static int replmd_replicated_uptodate_search_callback(struct ldb_request *req,
                                                      struct ldb_reply *ares)
 {
-       struct replmd_replicated_request *ar = talloc_get_type(private_data,
+       struct replmd_replicated_request *ar = talloc_get_type(req->context,
                                               struct replmd_replicated_request);
-       bool is_done = false;
+       int ret;
+
+       if (!ares) {
+               return ldb_module_done(ar->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS &&
+           ares->error != LDB_ERR_NO_SUCH_OBJECT) {
+               return ldb_module_done(ar->req, ares->controls,
+                                       ares->response, ares->error);
+       }
 
        switch (ares->type) {
        case LDB_REPLY_ENTRY:
-               ar->sub.search_msg = talloc_steal(ar->sub.mem_ctx, ares->message);
+               ar->search_msg = talloc_steal(ar, ares->message);
                break;
+
        case LDB_REPLY_REFERRAL:
                /* we ignore referrals */
                break;
-       case LDB_REPLY_EXTENDED:
-       case LDB_REPLY_DONE:
-               is_done = true;
-       }
-
-       talloc_free(ares);
 
-#ifdef REPLMD_FULL_ASYNC /* TODO: activate this code when ldb support full async code */ 
-       if (is_done) {
-               ar->sub.search_ret = ldb_wait(ar->sub.search_req->handle, LDB_WAIT_ALL);
-               if (ar->sub.search_ret != LDB_SUCCESS) {
-                       return replmd_replicated_request_error(ar, ar->sub.search_ret);
+       case LDB_REPLY_DONE:
+               if (ar->search_msg == NULL) {
+                       ret = replmd_replicated_request_werror(ar, WERR_DS_DRA_INTERNAL_ERROR);
+               } else {
+                       ret = replmd_replicated_uptodate_modify(ar);
                }
-               if (!ar->sub.search_msg) {
-                       return replmd_replicated_request_werror(ar, WERR_DS_DRA_INTERNAL_ERROR);
+               if (ret != LDB_SUCCESS) {
+                       return ldb_module_done(ar->req, NULL, NULL, ret);
                }
-
-               return replmd_replicated_uptodate_modify(ar);
        }
-#endif
+
+       talloc_free(ares);
        return LDB_SUCCESS;
 }
 
-static int replmd_replicated_uptodate_search(struct replmd_replicated_request *ar)
+
+static int replmd_replicated_uptodate_vector(struct replmd_replicated_request *ar)
 {
        int ret;
        static const char *attrs[] = {
@@ -1448,49 +1348,32 @@ static int replmd_replicated_uptodate_search(struct replmd_replicated_request *a
                "repsFrom",
                NULL
        };
+       struct ldb_request *search_req;
+
+       ar->search_msg = NULL;
 
-       ret = ldb_build_search_req(&ar->sub.search_req,
+       ret = ldb_build_search_req(&search_req,
                                   ar->module->ldb,
-                                  ar->sub.mem_ctx,
+                                  ar,
                                   ar->objs->partition_dn,
                                   LDB_SCOPE_BASE,
                                   "(objectClass=*)",
                                   attrs,
                                   NULL,
                                   ar,
-                                  replmd_replicated_uptodate_search_callback);
-       if (ret != LDB_SUCCESS) return replmd_replicated_request_error(ar, ret);
-
-#ifdef REPLMD_FULL_ASYNC /* TODO: activate this code when ldb support full async code */ 
-       return ldb_next_request(ar->module, ar->sub.search_req);
-#else
-       ret = ldb_next_request(ar->module, ar->sub.search_req);
+                                  replmd_replicated_uptodate_search_callback,
+                                  ar->req);
        if (ret != LDB_SUCCESS) return replmd_replicated_request_error(ar, ret);
 
-       ar->sub.search_ret = ldb_wait(ar->sub.search_req->handle, LDB_WAIT_ALL);
-       if (ar->sub.search_ret != LDB_SUCCESS) {
-               return replmd_replicated_request_error(ar, ar->sub.search_ret);
-       }
-       if (!ar->sub.search_msg) {
-               return replmd_replicated_request_werror(ar, WERR_DS_DRA_INTERNAL_ERROR);
-       }
-
-       return replmd_replicated_uptodate_modify(ar);
-#endif
-}
-
-static int replmd_replicated_uptodate_vector(struct replmd_replicated_request *ar)
-{
-       ar->sub.mem_ctx = talloc_new(ar);
-       if (!ar->sub.mem_ctx) return replmd_replicated_request_werror(ar, WERR_NOMEM);
-
-       return replmd_replicated_uptodate_search(ar);
+       return ldb_next_request(ar->module, search_req);
 }
 
 static int replmd_extended_replicated_objects(struct ldb_module *module, struct ldb_request *req)
 {
        struct dsdb_extended_replicated_objects *objs;
        struct replmd_replicated_request *ar;
+       struct ldb_control **ctrls;
+       int ret;
 
        ldb_debug(module->ldb, LDB_DEBUG_TRACE, "replmd_extended_replicated_objects\n");
 
@@ -1506,25 +1389,35 @@ static int replmd_extended_replicated_objects(struct ldb_module *module, struct
                return LDB_ERR_PROTOCOL_ERROR;
        }
 
-       ar = replmd_replicated_init_handle(module, req, objs);
-       if (!ar) {
+       ar = replmd_ctx_init(module, req);
+       if (!ar)
                return LDB_ERR_OPERATIONS_ERROR;
+
+       ar->objs = objs;
+       ar->schema = dsdb_get_schema(module->ldb);
+       if (!ar->schema) {
+               ldb_debug_set(module->ldb, LDB_DEBUG_FATAL, "replmd_ctx_init: no loaded schema found\n");
+               talloc_free(ar);
+               return LDB_ERR_CONSTRAINT_VIOLATION;
        }
 
-#ifdef REPLMD_FULL_ASYNC /* TODO: activate this code when ldb support full async code */ 
-       return replmd_replicated_apply_next(ar);
-#else
-       while (ar->index_current < ar->objs->num_objects &&
-              req->handle->state != LDB_ASYNC_DONE) { 
-               replmd_replicated_apply_next(ar);
+       ctrls = req->controls;
+
+       if (req->controls) {
+               req->controls = talloc_memdup(ar, req->controls,
+                                             talloc_get_size(req->controls));
+               if (!req->controls) return replmd_replicated_request_werror(ar, WERR_NOMEM);
        }
 
-       if (req->handle->state != LDB_ASYNC_DONE) {
-               replmd_replicated_uptodate_vector(ar);
+       ret = ldb_request_add_control(req, DSDB_CONTROL_REPLICATED_UPDATE_OID, false, NULL);
+       if (ret != LDB_SUCCESS) {
+               return ret;
        }
 
-       return LDB_SUCCESS;
-#endif
+       ar->controls = req->controls;
+       req->controls = ctrls;
+
+       return replmd_replicated_apply_next(ar);
 }
 
 static int replmd_extended(struct ldb_module *module, struct ldb_request *req)
@@ -1536,53 +1429,9 @@ static int replmd_extended(struct ldb_module *module, struct ldb_request *req)
        return ldb_next_request(module, req);
 }
 
-static int replmd_wait_none(struct ldb_handle *handle) {
-       struct replmd_replicated_request *ar;
-    
-       if (!handle || !handle->private_data) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       ar = talloc_get_type(handle->private_data, struct replmd_replicated_request);
-       if (!ar) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       /* we do only sync calls */
-       if (handle->state != LDB_ASYNC_DONE) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       return handle->status;
-}
-
-static int replmd_wait_all(struct ldb_handle *handle) {
-
-       int ret;
-
-       while (handle->state != LDB_ASYNC_DONE) {
-               ret = replmd_wait_none(handle);
-               if (ret != LDB_SUCCESS) {
-                       return ret;
-               }
-       }
-
-       return handle->status;
-}
-
-static int replmd_wait(struct ldb_handle *handle, enum ldb_wait_type type)
-{
-       if (type == LDB_WAIT_ALL) {
-               return replmd_wait_all(handle);
-       } else {
-               return replmd_wait_none(handle);
-       }
-}
-
 _PUBLIC_ const struct ldb_module_ops ldb_repl_meta_data_module_ops = {
        .name          = "repl_meta_data",
        .add           = replmd_add,
        .modify        = replmd_modify,
        .extended      = replmd_extended,
-       .wait          = replmd_wait
 };
index ebc90d4cf3c009761ae097057640dffa99fb7aec..b38e182cf7897ca4bbc8557e987ef57efa4c43fa 100644 (file)
@@ -4,7 +4,7 @@
    rootDSE ldb module
 
    Copyright (C) Andrew Tridgell 2005
-   Copyright (C) Simo Sorce 2005
+   Copyright (C) Simo Sorce 2005-2008
    
    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
@@ -221,40 +221,77 @@ failed:
 
 struct rootdse_context {
        struct ldb_module *module;
-       void *up_context;
-       int (*up_callback)(struct ldb_context *, void *, struct ldb_reply *);
-
-       const char * const * attrs;
+       struct ldb_request *req;
 };
 
-static int rootdse_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares)
+static struct rootdse_context *rootdse_init_context(struct ldb_module *module,
+                                                   struct ldb_request *req)
+{
+       struct rootdse_context *ac;
+
+       ac = talloc_zero(req, struct rootdse_context);
+       if (ac == NULL) {
+               ldb_set_errstring(module->ldb, "Out of Memory");
+               return NULL;
+       }
+
+       ac->module = module;
+       ac->req = req;
+
+       return ac;
+}
+
+static int rootdse_callback(struct ldb_request *req, struct ldb_reply *ares)
 {
        struct rootdse_context *ac;
+       int ret;
+
+       ac = talloc_get_type(req->context, struct rootdse_context);
 
-       ac = talloc_get_type(context, struct rootdse_context);
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
 
-       if (ares->type == LDB_REPLY_ENTRY) {
+       switch (ares->type) {
+       case LDB_REPLY_ENTRY:
                /*
                 * if the client explicit asks for the 'netlogon' attribute
                 * the reply_entry needs to be skipped
                 */
-               if (ac->attrs && ldb_attr_in_list(ac->attrs, "netlogon")) {
+               if (ac->req->op.search.attrs &&
+                   ldb_attr_in_list(ac->req->op.search.attrs, "netlogon")) {
                        talloc_free(ares);
                        return LDB_SUCCESS;
                }
 
                /* for each record returned post-process to add any dynamic
                   attributes that have been asked for */
-               if (rootdse_add_dynamic(ac->module, ares->message, ac->attrs) != LDB_SUCCESS) {
-                       goto error;
+               ret = rootdse_add_dynamic(ac->module, ares->message,
+                                         ac->req->op.search.attrs);
+               if (ret != LDB_SUCCESS) {
+                       talloc_free(ares);
+                       return ldb_module_done(ac->req, NULL, NULL, ret);
                }
-       }
 
-       return ac->up_callback(ldb, ac->up_context, ares);
+               return ldb_module_send_entry(ac->req, ares->message);
+
+       case LDB_REPLY_REFERRAL:
+               /* should we allow the backend to return referrals in this case
+                * ?? */
+               break;
+
+       case LDB_REPLY_DONE:
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
 
-error:
        talloc_free(ares);
-       return LDB_ERR_OPERATIONS_ERROR;
+       return LDB_SUCCESS;
 }
 
 static int rootdse_search(struct ldb_module *module, struct ldb_request *req)
@@ -270,48 +307,25 @@ static int rootdse_search(struct ldb_module *module, struct ldb_request *req)
                return ldb_next_request(module, req);
        }
 
-       ac = talloc(req, struct rootdse_context);
+       ac = rootdse_init_context(module, req);
        if (ac == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       ac->module = module;
-       ac->up_context = req->context;
-       ac->up_callback = req->callback;
-       ac->attrs = req->op.search.attrs;
-
-       down_req = talloc_zero(req, struct ldb_request);
-       if (down_req == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       down_req->operation = req->operation;
        /* in our db we store the rootDSE with a DN of @ROOTDSE */
-       down_req->op.search.base = ldb_dn_new(down_req, module->ldb, "@ROOTDSE");
-       down_req->op.search.scope = LDB_SCOPE_BASE;
-       down_req->op.search.tree = ldb_parse_tree(down_req, NULL);
-       if (down_req->op.search.base == NULL || down_req->op.search.tree == NULL) {
-               ldb_oom(module->ldb);
-               talloc_free(down_req);
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-       down_req->op.search.attrs = req->op.search.attrs;
-       down_req->controls = req->controls;
-
-       down_req->context = ac;
-       down_req->callback = rootdse_callback;
-       ldb_set_timeout_from_prev_req(module->ldb, req, down_req);
-
-       /* perform the search */
-       ret = ldb_next_request(module, down_req);
-
-       /* do not free down_req as the call results may be linked to it,
-        * it will be freed when the upper level request get freed */
-       if (ret == LDB_SUCCESS) {
-               req->handle = down_req->handle;
+       ret = ldb_build_search_req(&down_req, module->ldb, ac,
+                                       ldb_dn_new(ac, module->ldb, "@ROOTDSE"),
+                                       LDB_SCOPE_BASE,
+                                       NULL,
+                                       req->op.search.attrs,
+                                       NULL,/* for now skip the controls from the client */
+                                       ac, rootdse_callback,
+                                       req);
+       if (ret != LDB_SUCCESS) {
+               return ret;
        }
 
-       return ret;
+       return ldb_next_request(module, down_req);
 }
 
 static int rootdse_register_control(struct ldb_module *module, struct ldb_request *req)
@@ -332,9 +346,9 @@ static int rootdse_register_control(struct ldb_module *module, struct ldb_reques
        priv->num_controls += 1;
        priv->controls = list;
 
-       return LDB_SUCCESS;
+       return ldb_module_done(req, NULL, NULL, LDB_SUCCESS);
 }
+
 static int rootdse_register_partition(struct ldb_module *module, struct ldb_request *req)
 {
        struct private_data *priv = talloc_get_type(module->private_data, struct private_data);
@@ -353,9 +367,9 @@ static int rootdse_register_partition(struct ldb_module *module, struct ldb_requ
        priv->num_partitions += 1;
        priv->partitions = list;
 
-       return LDB_SUCCESS;
+       return ldb_module_done(req, NULL, NULL, LDB_SUCCESS);
 }
+
 
 static int rootdse_request(struct ldb_module *module, struct ldb_request *req)
 {
index cf720669b94f99616e41049f9eb92c2e0eb303ba..a71ffff61853afcbdc1ea23f1f26189505b04c59 100644 (file)
@@ -1,8 +1,8 @@
-/* 
+/*
    SAM ldb module
 
-   Copyright (C) Simo Sorce  2004
    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005
+   Copyright (C) Simo Sorce  2004-2008
 
    * NOTICE: this module is NOT released under the GNU LGPL license as
    * other ldb code. This module is release under the GNU GPL v3 or
    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 "lib/ldb/include/ldb_errors.h"
 #include "lib/ldb/include/ldb.h"
 #include "lib/ldb/include/ldb_private.h"
+#include "lib/events/events.h"
 #include "dsdb/samdb/samdb.h"
 #include "libcli/security/security.h"
 #include "librpc/gen_ndr/ndr_security.h"
 #include "util/util_ldb.h"
+#include "ldb_wrap.h"
+
+struct samldb_ctx;
+
+typedef int (*samldb_step_fn_t)(struct samldb_ctx *);
+
+struct samldb_step {
+       struct samldb_step *next;
+       samldb_step_fn_t fn;
+};
+
+struct samldb_ctx {
+       struct ldb_module *module;
+       struct ldb_request *req;
 
-int samldb_notice_sid(struct ldb_module *module, 
-                     TALLOC_CTX *mem_ctx, const struct dom_sid *sid);
+       /* the resulting message */
+       struct ldb_message *msg;
+
+       /* used to apply templates */
+       const char *type;
+
+       /* used to find parent domain */
+       struct ldb_dn *check_dn;
+       struct ldb_dn *domain_dn;
+       struct dom_sid *domain_sid;
+       uint32_t next_rid;
+
+       /* generic storage, remember to zero it before use */
+       struct ldb_reply *ares;
+
+       /* holds the entry SID */
+       struct dom_sid *sid;
+
+       /* all the async steps necessary to complete the operation */
+       struct samldb_step *steps;
+       struct samldb_step *curstep;
+};
 
-static bool samldb_msg_add_sid(struct ldb_module *module, struct ldb_message *msg, const char *name, const struct dom_sid *sid)
+struct samldb_ctx *samldb_ctx_init(struct ldb_module *module,
+                                  struct ldb_request *req)
 {
-       struct ldb_val v;
-       enum ndr_err_code ndr_err;
+       struct samldb_ctx *ac;
 
-       ndr_err = ndr_push_struct_blob(&v, msg, NULL, sid,
-                                      (ndr_push_flags_fn_t)ndr_push_dom_sid);
-       if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
-               return false;
+       ac = talloc_zero(req, struct samldb_ctx);
+       if (ac == NULL) {
+               ldb_oom(module->ldb);
+               return NULL;
        }
-       return (ldb_msg_add_value(msg, name, &v, NULL) == 0);
+
+       ac->module = module;
+       ac->req = req;
+
+       return ac;
 }
 
-/*
-  allocate a new id, attempting to do it atomically
-  return 0 on failure, the id on success
-*/
-static int samldb_set_next_rid(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
-                              struct ldb_dn *dn, uint32_t old_id, uint32_t new_id)
+static int samldb_add_step(struct samldb_ctx *ac, samldb_step_fn_t fn)
 {
-       struct ldb_message msg;
-       int ret;
-       struct ldb_val vals[2];
-       struct ldb_message_element els[2];
+       struct samldb_step *step;
 
-       if (new_id == 0) {
-               /* out of IDs ! */
-               ldb_set_errstring(ldb, "Are we out of valid IDs ?\n");
+       step = talloc_zero(ac, struct samldb_step);
+       if (step == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       /* we do a delete and add as a single operation. That prevents
-          a race, in case we are not actually on a transaction db */
-       ZERO_STRUCT(msg);
-       msg.dn = ldb_dn_copy(mem_ctx, dn);
-       if (!msg.dn) {
-               ldb_oom(ldb);
-               return LDB_ERR_OPERATIONS_ERROR;
+       if (ac->steps == NULL) {
+               ac->steps = step;
+               ac->curstep = step;
+       } else {
+               ac->curstep->next = step;
+               ac->curstep = step;
        }
-       msg.num_elements = 2;
-       msg.elements = els;
 
-       els[0].num_values = 1;
-       els[0].values = &vals[0];
-       els[0].flags = LDB_FLAG_MOD_DELETE;
-       els[0].name = talloc_strdup(mem_ctx, "nextRid");
-       if (!els[0].name) {
-               ldb_oom(ldb);
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
+       step->fn = fn;
 
-       els[1].num_values = 1;
-       els[1].values = &vals[1];
-       els[1].flags = LDB_FLAG_MOD_ADD;
-       els[1].name = els[0].name;
+       return LDB_SUCCESS;
+}
 
-       vals[0].data = (uint8_t *)talloc_asprintf(mem_ctx, "%u", old_id);
-       if (!vals[0].data) {
-               ldb_oom(ldb);
+static int samldb_first_step(struct samldb_ctx *ac)
+{
+       if (ac->steps == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       vals[0].length = strlen((char *)vals[0].data);
 
-       vals[1].data = (uint8_t *)talloc_asprintf(mem_ctx, "%u", new_id);
-       if (!vals[1].data) {
-               ldb_oom(ldb);
-               return LDB_ERR_OPERATIONS_ERROR;
+       ac->curstep = ac->steps;
+       return ac->curstep->fn(ac);
+}
+
+static int samldb_next_step(struct samldb_ctx *ac)
+{
+       if (ac->curstep->next) {
+               ac->curstep = ac->curstep->next;
+               return ac->curstep->fn(ac);
        }
-       vals[1].length = strlen((char *)vals[1].data);
 
-       ret = ldb_modify(ldb, &msg);
-       return ret;
+       /* it is an error if the last step does not properly
+        * return to the upper module by itself */
+       return LDB_ERR_OPERATIONS_ERROR;
 }
 
-/*
-  allocate a new id, attempting to do it atomically
-  return 0 on failure, the id on success
-*/
-static int samldb_find_next_rid(struct ldb_module *module, TALLOC_CTX *mem_ctx,
-                               struct ldb_dn *dn, uint32_t *old_rid)
+static int samldb_search_template_callback(struct ldb_request *req,
+                                          struct ldb_reply *ares)
 {
-       const char * const attrs[2] = { "nextRid", NULL };
-       struct ldb_result *res = NULL;
+       struct samldb_ctx *ac;
        int ret;
-       const char *str;
 
-       ret = ldb_search(module->ldb, mem_ctx, &res, dn, LDB_SCOPE_BASE, attrs, "nextRid=*");
-       if (ret != LDB_SUCCESS) {
-               return ret;
+       ac = talloc_get_type(req->context, struct samldb_ctx);
+
+       if (!ares) {
+               ret = LDB_ERR_OPERATIONS_ERROR;
+               goto done;
        }
-       if (res->count != 1) {
-               talloc_free(res);
-               return LDB_ERR_OPERATIONS_ERROR;
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
        }
 
-       str = ldb_msg_find_attr_as_string(res->msgs[0], "nextRid", NULL);
-       if (str == NULL) {
-               ldb_asprintf_errstring(module->ldb,
-                                       "attribute nextRid not found in %s\n",
-                                       ldb_dn_get_linearized(dn));
-               talloc_free(res);
-               return LDB_ERR_OPERATIONS_ERROR;
+       switch (ares->type) {
+       case LDB_REPLY_ENTRY:
+               /* save entry */
+               if (ac->ares != NULL) {
+                       /* one too many! */
+                       ldb_set_errstring(ac->module->ldb,
+                               "Invalid number of results while searching "
+                               "for template objects");
+                       ret = LDB_ERR_OPERATIONS_ERROR;
+                       goto done;
+               }
+
+               ac->ares = talloc_steal(ac, ares);
+               ret = LDB_SUCCESS;
+               break;
+
+       case LDB_REPLY_REFERRAL:
+               /* ignore */
+               talloc_free(ares);
+               ret = LDB_SUCCESS;
+               break;
+
+       case LDB_REPLY_DONE:
+
+               talloc_free(ares);
+               ret = samldb_next_step(ac);
+               break;
+       }
+
+done:
+       if (ret != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, NULL, NULL, ret);
        }
 
-       *old_rid = strtol(str, NULL, 0);
-       talloc_free(res);
        return LDB_SUCCESS;
 }
 
-static int samldb_allocate_next_rid(struct ldb_module *module, TALLOC_CTX *mem_ctx,
-                                   struct ldb_dn *dn, const struct dom_sid *dom_sid, 
-                                   struct dom_sid **new_sid)
+static int samldb_search_template(struct samldb_ctx *ac)
 {
-       struct dom_sid *obj_sid;
-       uint32_t old_rid;
+       struct event_context *ev;
+       struct loadparm_context *lparm_ctx;
+       struct ldb_context *templates_ldb;
+       char *templates_ldb_path;
+       struct ldb_request *req;
+       struct ldb_dn *basedn;
+       void *opaque;
        int ret;
-       
-       ret = samldb_find_next_rid(module, mem_ctx, dn, &old_rid);      
-       if (ret) {
-               return ret;
+
+       opaque = ldb_get_opaque(ac->module->ldb, "loadparm");
+       lparm_ctx = talloc_get_type(opaque, struct loadparm_context);
+       if (lparm_ctx == NULL) {
+               ldb_set_errstring(ac->module->ldb,
+                       "Unable to find loadparm context\n");
+               return LDB_ERR_OPERATIONS_ERROR;
        }
-               
-       /* return the new object sid */
-       obj_sid = dom_sid_add_rid(mem_ctx, dom_sid, old_rid);
-               
-       *new_sid = dom_sid_add_rid(mem_ctx, dom_sid, old_rid + 1);
-       if (!*new_sid) {
+
+       opaque = ldb_get_opaque(ac->module->ldb, "templates_ldb");
+       templates_ldb = talloc_get_type(opaque, struct ldb_context);
+
+       /* make sure we have the templates ldb */
+       if (!templates_ldb) {
+               templates_ldb_path = samdb_relative_path(ac->module->ldb, ac,
+                                                        "templates.ldb");
+               if (!templates_ldb_path) {
+                       ldb_set_errstring(ac->module->ldb,
+                                       "samldb_init_template: ERROR: Failed "
+                                       "to contruct path for template db");
+                       return LDB_ERR_OPERATIONS_ERROR;
+               }
+
+               ev = ldb_get_event_context(ac->module->ldb);
+
+               templates_ldb = ldb_wrap_connect(ac->module->ldb, ev,
+                                               lparm_ctx, templates_ldb_path,
+                                               NULL, NULL, 0, NULL);
+               talloc_free(templates_ldb_path);
+
+               if (!templates_ldb) {
+                       return LDB_ERR_OPERATIONS_ERROR;
+               }
+
+               if (!talloc_reference(templates_ldb, ev)) {
+                       return LDB_ERR_OPERATIONS_ERROR;
+               }
+
+               ret = ldb_set_opaque(ac->module->ldb,
+                                       "templates_ldb", templates_ldb);
+               if (ret != LDB_SUCCESS) {
+                       return ret;
+               }
+       }
+
+       /* search template */
+       basedn = ldb_dn_new_fmt(ac, templates_ldb,
+                           "cn=Template%s,cn=Templates", ac->type);
+       if (basedn == NULL) {
+               ldb_set_errstring(ac->module->ldb,
+                       "samldb_init_template: ERROR: Failed "
+                       "to contruct DN for template");
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       ret = samldb_notice_sid(module, mem_ctx, *new_sid);
-       if (ret != 0) {
-               /* gah, there are conflicting sids.
-                * This is a critical situation it means that someone messed up with
-                * the DB and nextRid is not returning free RIDs, report an error
-                * and refuse to create any user until the problem is fixed */
-               ldb_asprintf_errstring(module->ldb,
-                                       "Critical Error: unconsistent DB, unable to retireve an unique RID to generate a new SID: %s",
-                                       ldb_errstring(module->ldb));
+       /* pull the template record */
+       ret = ldb_build_search_req(&req, templates_ldb, ac,
+                                  basedn, LDB_SCOPE_BASE,
+                                 "(distinguishedName=*)", NULL,
+                                 NULL,
+                                 ac, samldb_search_template_callback,
+                                 ac->req);
+       if (ret != LDB_SUCCESS) {
                return ret;
        }
-       return ret;
+
+       talloc_steal(req, basedn);
+       ac->ares = NULL;
+
+       return ldb_request(templates_ldb, req);
 }
 
-/* search the domain related to the provided dn
-   allocate a new RID for the domain
-   return the new sid string
-*/
-static int samldb_get_new_sid(struct ldb_module *module, 
-                             TALLOC_CTX *mem_ctx, struct ldb_dn *obj_dn,
-                             struct ldb_dn *dom_dn, 
-                             struct dom_sid **sid)
+static int samldb_apply_template(struct samldb_ctx *ac)
+{
+       struct ldb_message_element *el;
+       struct ldb_message *msg;
+       int i, j;
+       int ret;
+
+       msg = ac->ares->message;
+
+       for (i = 0; i < msg->num_elements; i++) {
+               el = &msg->elements[i];
+               /* some elements should not be copied */
+               if (ldb_attr_cmp(el->name, "cn") == 0 ||
+                   ldb_attr_cmp(el->name, "name") == 0 ||
+                   ldb_attr_cmp(el->name, "objectClass") == 0 ||
+                   ldb_attr_cmp(el->name, "sAMAccountName") == 0 ||
+                   ldb_attr_cmp(el->name, "sAMAccountName") == 0 ||
+                   ldb_attr_cmp(el->name, "distinguishedName") == 0 ||
+                   ldb_attr_cmp(el->name, "objectGUID") == 0) {
+                       continue;
+               }
+               for (j = 0; j < el->num_values; j++) {
+                       ret = samdb_find_or_add_attribute(
+                                       ac->module->ldb, ac->msg, el->name,
+                                       (char *)el->values[j].data);
+                       if (ret != LDB_SUCCESS) {
+                               ldb_set_errstring(ac->module->ldb,
+                                         "Failed adding template attribute\n");
+                               return LDB_ERR_OPERATIONS_ERROR;
+                       }
+               }
+       }
+
+       return samldb_next_step(ac);
+}
+
+static int samldb_get_parent_domain(struct samldb_ctx *ac);
+
+static int samldb_get_parent_domain_callback(struct ldb_request *req,
+                                            struct ldb_reply *ares)
 {
-       const char * const attrs[2] = { "objectSid", NULL };
-       struct ldb_result *res = NULL;
+       struct samldb_ctx *ac;
+       const char *nextRid;
        int ret;
-       struct dom_sid *dom_sid;
 
-       /* get the domain component part of the provided dn */
+       ac = talloc_get_type(req->context, struct samldb_ctx);
+
+       if (!ares) {
+               ret = LDB_ERR_OPERATIONS_ERROR;
+               goto done;
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
+
+       switch (ares->type) {
+       case LDB_REPLY_ENTRY:
+               /* save entry */
+               if (ac->domain_dn != NULL) {
+                       /* one too many! */
+                       ldb_set_errstring(ac->module->ldb,
+                               "Invalid number of results while searching "
+                               "for domain object");
+                       ret = LDB_ERR_OPERATIONS_ERROR;
+                       break;
+               }
+
+               nextRid = ldb_msg_find_attr_as_string(ares->message,
+                                                       "nextRid", NULL);
+               if (nextRid == NULL) {
+                       ldb_asprintf_errstring(ac->module->ldb,
+                               "attribute nextRid not found in %s\n",
+                               ldb_dn_get_linearized(ares->message->dn));
+                       ret = LDB_ERR_OPERATIONS_ERROR;
+                       break;;
+               }
+
+               ac->next_rid = strtol(nextRid, NULL, 0);
+
+               ac->domain_sid = samdb_result_dom_sid(ac, ares->message,
+                                                               "objectSid");
+               if (ac->domain_sid == NULL) {
+                       ldb_set_errstring(ac->module->ldb,
+                               "error retrieving parent domain domain sid!\n");
+                       ret = LDB_ERR_CONSTRAINT_VIOLATION;
+                       break;
+               }
+               ac->domain_dn = talloc_steal(ac, ares->message->dn);
+
+               talloc_free(ares);
+               ret = LDB_SUCCESS;
+               break;
+
+       case LDB_REPLY_REFERRAL:
+               /* ignore */
+               talloc_free(ares);
+               ret = LDB_SUCCESS;
+               break;
 
-       /* find the domain sid */
+       case LDB_REPLY_DONE:
 
-       ret = ldb_search(module->ldb, mem_ctx, &res, dom_dn, LDB_SCOPE_BASE, attrs, "objectSid=*");
+               talloc_free(ares);
+               if (ac->domain_dn == NULL) {
+                       /* search again */
+                       ret = samldb_get_parent_domain(ac);
+               } else {
+                       /* found, go on */
+                       ret = samldb_next_step(ac);
+               }
+               break;
+       }
+
+done:
        if (ret != LDB_SUCCESS) {
-               ldb_asprintf_errstring(module->ldb,
-                                       "samldb_get_new_sid: error retrieving domain sid from %s: %s!\n",
-                                       ldb_dn_get_linearized(dom_dn),
-                                       ldb_errstring(module->ldb));
-               talloc_free(res);
-               return ret;
+               return ldb_module_done(ac->req, NULL, NULL, ret);
        }
 
-       if (res->count != 1) {
-               ldb_asprintf_errstring(module->ldb,
-                                       "samldb_get_new_sid: error retrieving domain sid from %s: not found!\n",
-                                       ldb_dn_get_linearized(dom_dn));
-               talloc_free(res);
-               return LDB_ERR_CONSTRAINT_VIOLATION;
+       return LDB_SUCCESS;
+}
+
+/* Find a domain object in the parents of a particular DN.  */
+static int samldb_get_parent_domain(struct samldb_ctx *ac)
+{
+       static const char * const attrs[3] = { "objectSid", "nextRid", NULL };
+       struct ldb_request *req;
+       struct ldb_dn *dn;
+       int ret;
+
+       if (ac->check_dn == NULL) {
+               return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       dom_sid = samdb_result_dom_sid(res, res->msgs[0], "objectSid");
-       if (dom_sid == NULL) {
-               ldb_set_errstring(module->ldb, "samldb_get_new_sid: error parsing domain sid!\n");
-               talloc_free(res);
+       dn = ldb_dn_get_parent(ac, ac->check_dn);
+       if (dn == NULL) {
+               ldb_set_errstring(ac->module->ldb,
+                       "Unable to find parent domain object");
                return LDB_ERR_CONSTRAINT_VIOLATION;
        }
 
-       /* allocate a new Rid for the domain */
-       ret = samldb_allocate_next_rid(module, mem_ctx, dom_dn, dom_sid, sid);
-       if (ret != 0) {
-               ldb_debug(module->ldb, LDB_DEBUG_FATAL, "Failed to increment nextRid of %s: %s\n", ldb_dn_get_linearized(dom_dn), ldb_errstring(module->ldb));
-               talloc_free(res);
+       ac->check_dn = dn;
+
+       ret = ldb_build_search_req(&req, ac->module->ldb, ac,
+                                  dn, LDB_SCOPE_BASE,
+                                  "(|(objectClass=domain)"
+                                    "(objectClass=builtinDomain)"
+                                    "(objectClass=samba4LocalDomain))",
+                                  attrs,
+                                  NULL,
+                                  ac, samldb_get_parent_domain_callback,
+                                  ac->req);
+
+       if (ret != LDB_SUCCESS) {
                return ret;
        }
 
-       talloc_free(res);
+       return ldb_next_request(ac->module, req);
+}
+
+static int samldb_generate_samAccountName(struct ldb_message *msg)
+{
+       char *name;
+
+       /* Format: $000000-000000000000 */
 
-       return ret;
+       name = talloc_asprintf(msg, "$%.6X-%.6X%.6X",
+                               (unsigned int)generate_random(),
+                               (unsigned int)generate_random(),
+                               (unsigned int)generate_random());
+       if (name == NULL) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+       return ldb_msg_add_steal_string(msg, "samAccountName", name);
 }
 
-/* If we are adding new users/groups, we need to update the nextRid
- * attribute to be 'above' all incoming users RIDs.  This tries to
- * avoid clashes in future */
+static int samldb_check_samAccountName_callback(struct ldb_request *req,
+                                               struct ldb_reply *ares)
+{
+       struct samldb_ctx *ac;
+       int ret;
+
+       ac = talloc_get_type(req->context, struct samldb_ctx);
 
-int samldb_notice_sid(struct ldb_module *module, 
-                     TALLOC_CTX *mem_ctx, const struct dom_sid *sid)
+       if (!ares) {
+               ret = LDB_ERR_OPERATIONS_ERROR;
+               goto done;
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
+
+       switch (ares->type) {
+       case LDB_REPLY_ENTRY:
+
+               /* if we get an entry it means this samAccountName
+                * already exists */
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_ENTRY_ALREADY_EXISTS);
+
+       case LDB_REPLY_REFERRAL:
+               /* ignore */
+               talloc_free(ares);
+               ret = LDB_SUCCESS;
+               break;
+
+       case LDB_REPLY_DONE:
+
+               /* not found, go on */
+               talloc_free(ares);
+               ret = samldb_next_step(ac);
+               break;
+       }
+
+done:
+       if (ret != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, NULL, NULL, ret);
+       }
+
+       return LDB_SUCCESS;
+}
+
+static int samldb_check_samAccountName(struct samldb_ctx *ac)
 {
+       struct ldb_request *req;
+       const char *name;
+       char *filter;
        int ret;
-       struct ldb_dn *dom_dn;
-       struct dom_sid *dom_sid;
-       const char *attrs[] = { NULL };
-       struct ldb_result *dom_res;
-       struct ldb_result *res;
-       uint32_t old_rid;
-
-       /* find if this SID already exists */
-       ret = ldb_search(module->ldb, mem_ctx, &res,
-                                NULL, LDB_SCOPE_SUBTREE, attrs,
-                                "(objectSid=%s)", ldap_encode_ndr_dom_sid(mem_ctx, sid));
-       if (ret == LDB_SUCCESS) {
-               if (res->count > 0) {
-                       talloc_free(res);
-                       ldb_asprintf_errstring(module->ldb,
-                                               "Attempt to add record with SID %s rejected,"
-                                               " because this SID is already in the database",
-                                               dom_sid_string(mem_ctx, sid));
-                       /* We have a duplicate SID, we must reject the add */
-                       return LDB_ERR_CONSTRAINT_VIOLATION;
+
+       if (ldb_msg_find_element(ac->msg, "samAccountName") == NULL) {
+               ret = samldb_generate_samAccountName(ac->msg);
+               if (ret != LDB_SUCCESS) {
+                       return ret;
                }
-               talloc_free(res);
-       } else {
-               ldb_asprintf_errstring(module->ldb,
-                                       "samldb_notice_sid: error searching to see if sid %s is in use: %s\n", 
-                                       dom_sid_string(mem_ctx, sid), 
-                                       ldb_errstring(module->ldb));
-               return ret;
        }
 
-       dom_sid = dom_sid_dup(mem_ctx, sid);
-       if (!dom_sid) {
+       name = ldb_msg_find_attr_as_string(ac->msg, "samAccountName", NULL);
+       if (name == NULL) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+       filter = talloc_asprintf(ac, "samAccountName=%s", name);
+       if (filter == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       /* get the domain component part of the provided SID */
-       dom_sid->num_auths--;
-
-       /* find the domain DN */
-       ret = ldb_search(module->ldb, mem_ctx, &dom_res,
-                                NULL, LDB_SCOPE_SUBTREE, attrs,
-                                "(&(objectSid=%s)(|(|(objectClass=domain)(objectClass=builtinDomain))(objectClass=samba4LocalDomain)))", 
-                                ldap_encode_ndr_dom_sid(mem_ctx, dom_sid));
-       if (ret == LDB_SUCCESS) {
-               if (dom_res->count == 0) {
-                       talloc_free(dom_res);
-                       /* This isn't an operation on a domain we know about, so nothing to update */
-                       return LDB_SUCCESS;
-               }
 
-               if (dom_res->count > 1) {
-                       talloc_free(dom_res);
-                       ldb_asprintf_errstring(module->ldb,
-                                       "samldb_notice_sid: error retrieving domain from sid: duplicate (found %d) domain: %s!\n", 
-                                       dom_res->count, dom_sid_string(dom_res, dom_sid));
-                       return LDB_ERR_OPERATIONS_ERROR;
-               }
-       } else {
-               ldb_asprintf_errstring(module->ldb,
-                                       "samldb_notice_sid: error retrieving domain from sid: %s: %s\n", 
-                                       dom_sid_string(dom_res, dom_sid), 
-                                       ldb_errstring(module->ldb));
+       ret = ldb_build_search_req(&req, ac->module->ldb, ac,
+                               ac->domain_dn, LDB_SCOPE_SUBTREE,
+                               filter, NULL,
+                               NULL,
+                               ac, samldb_check_samAccountName_callback,
+                               ac->req);
+       talloc_free(filter);
+       if (ret != LDB_SUCCESS) {
                return ret;
        }
+       ac->ares = NULL;
+       return ldb_next_request(ac->module, req);
+}
 
-       dom_dn = dom_res->msgs[0]->dn;
+static int samldb_check_samAccountType(struct samldb_ctx *ac)
+{
+       unsigned int account_type;
+       unsigned int group_type;
+       unsigned int uac;
+       int ret;
 
-       ret = samldb_find_next_rid(module, mem_ctx, 
-                                  dom_dn, &old_rid);
-       if (ret) {
-               talloc_free(dom_res);
-               return ret;
+       /* make sure sAMAccountType is not specified */
+       if (ldb_msg_find_element(ac->msg, "sAMAccountType") != NULL) {
+               ldb_asprintf_errstring(ac->module->ldb,
+                                       "sAMAccountType must not be specified");
+               return LDB_ERR_UNWILLING_TO_PERFORM;
        }
 
-       if (old_rid <= sid->sub_auths[sid->num_auths - 1]) {
-               ret = samldb_set_next_rid(module->ldb, mem_ctx, dom_dn, old_rid, 
-                                         sid->sub_auths[sid->num_auths - 1] + 1);
+       if (strcmp("user", ac->type) == 0) {
+               uac = samdb_result_uint(ac->msg, "userAccountControl", 0);
+               if (uac == 0) {
+                       ldb_asprintf_errstring(ac->module->ldb,
+                                               "userAccountControl invalid");
+                       return LDB_ERR_UNWILLING_TO_PERFORM;
+               } else {
+                       account_type = samdb_uf2atype(uac);
+                       ret = samdb_msg_add_uint(ac->module->ldb,
+                                                ac->msg, ac->msg,
+                                                "sAMAccountType",
+                                                account_type);
+                       if (ret != LDB_SUCCESS) {
+                               return ret;
+                       }
+               }
+       } else
+       if (strcmp("group", ac->type) == 0) {
+
+               group_type = samdb_result_uint(ac->msg, "groupType", 0);
+               if (group_type == 0) {
+                       ldb_asprintf_errstring(ac->module->ldb,
+                                               "groupType invalid");
+                       return LDB_ERR_UNWILLING_TO_PERFORM;
+               } else {
+                       account_type = samdb_gtype2atype(group_type);
+                       ret = samdb_msg_add_uint(ac->module->ldb,
+                                                ac->msg, ac->msg,
+                                                "sAMAccountType",
+                                                account_type);
+                       if (ret != LDB_SUCCESS) {
+                               return ret;
+                       }
+               }
        }
-       talloc_free(dom_res);
-       return ret;
+
+       return samldb_next_step(ac);
 }
 
-static int samldb_handle_sid(struct ldb_module *module, 
-                            TALLOC_CTX *mem_ctx, struct ldb_message *msg2,
-                            struct ldb_dn *parent_dn)
+static int samldb_get_sid_domain_callback(struct ldb_request *req,
+                                         struct ldb_reply *ares)
 {
+       struct samldb_ctx *ac;
+       const char *nextRid;
        int ret;
-       
-       struct dom_sid *sid = samdb_result_dom_sid(mem_ctx, msg2, "objectSid");
-       if (sid == NULL) { 
-               ret = samldb_get_new_sid(module, msg2, msg2->dn, parent_dn, &sid);
-               if (ret != 0) {
-                       return ret;
+
+       ac = talloc_get_type(req->context, struct samldb_ctx);
+
+       if (!ares) {
+               ret = LDB_ERR_OPERATIONS_ERROR;
+               goto done;
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
+
+       switch (ares->type) {
+       case LDB_REPLY_ENTRY:
+               /* save entry */
+               if (ac->next_rid != 0) {
+                       /* one too many! */
+                       ldb_set_errstring(ac->module->ldb,
+                               "Invalid number of results while searching "
+                               "for domain object");
+                       ret = LDB_ERR_OPERATIONS_ERROR;
+                       break;
                }
 
-               if ( ! samldb_msg_add_sid(module, msg2, "objectSid", sid)) {
-                       talloc_free(sid);
-                       return LDB_ERR_OPERATIONS_ERROR;
+               nextRid = ldb_msg_find_attr_as_string(ares->message,
+                                                       "nextRid", NULL);
+               if (nextRid == NULL) {
+                       ldb_asprintf_errstring(ac->module->ldb,
+                               "attribute nextRid not found in %s\n",
+                               ldb_dn_get_linearized(ares->message->dn));
+                       ret = LDB_ERR_OPERATIONS_ERROR;
+                       break;
                }
-               talloc_free(sid);
+
+               ac->next_rid = strtol(nextRid, NULL, 0);
+
+               ac->domain_dn = talloc_steal(ac, ares->message->dn);
+
+               talloc_free(ares);
                ret = LDB_SUCCESS;
-       } else {
-               ret = samldb_notice_sid(module, msg2, sid);
+               break;
+
+       case LDB_REPLY_REFERRAL:
+               /* ignore */
+               talloc_free(ares);
+               ret = LDB_SUCCESS;
+               break;
+
+       case LDB_REPLY_DONE:
+
+               if (ac->next_rid == 0) {
+                       ldb_asprintf_errstring(ac->module->ldb,
+                               "Unable to get nextRid from domain entry\n");
+                       ret = LDB_ERR_OPERATIONS_ERROR;
+                       break;
+               }
+
+               /* found, go on */
+               ret = samldb_next_step(ac);
+               break;
+       }
+
+done:
+       if (ret != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, NULL, NULL, ret);
        }
-       return ret;
+
+       return LDB_SUCCESS;
 }
 
-static int samldb_generate_samAccountName(struct ldb_module *module, TALLOC_CTX *mem_ctx, 
-                                         struct ldb_dn *dom_dn, char **name) 
+/* Find a domain object in the parents of a particular DN.  */
+static int samldb_get_sid_domain(struct samldb_ctx *ac)
 {
-       const char *attrs[] = { NULL };
-       struct ldb_result *res;
+       static const char * const attrs[2] = { "nextRid", NULL };
+       struct ldb_request *req;
+       char *filter;
        int ret;
-       
-       /* Format: $000000-000000000000 */
-       
-       do {
-               *name = talloc_asprintf(mem_ctx, "$%.6X-%.6X%.6X", (unsigned int)generate_random(), (unsigned int)generate_random(), (unsigned int)generate_random());
-               /* TODO: Figure out exactly what this is meant to conflict with */
-               ret = ldb_search(module->ldb,
-                                        mem_ctx, &res, dom_dn, LDB_SCOPE_SUBTREE, attrs,
-                                        "samAccountName=%s",
-                                        ldb_binary_encode_string(mem_ctx, *name));
-               if (ret != LDB_SUCCESS) {
-                       ldb_asprintf_errstring(module->ldb, "samldb: Failure searching to determine if samAccountName %s is unique: %s",
-                                              *name, ldb_errstring(module->ldb));
-                       return ret;
-               }
 
-               if (res->count == 0) {
-                       talloc_free(res);
-                       /* Great. There are no conflicting users/groups/etc */
-                       return LDB_SUCCESS;
-               } else {
-                       talloc_free(*name);
-                        /* gah, there is a conflicting name, lets move around the loop again... */
-               }
-       } while (1);
+       if (ac->sid == NULL) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       ac->domain_sid = dom_sid_dup(ac, ac->sid);
+       if (!ac->domain_sid) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+       /* get the domain component part of the provided SID */
+       ac->domain_sid->num_auths--;
+
+       filter = talloc_asprintf(ac, "(&(objectSid=%s)"
+                                      "(|(objectClass=domain)"
+                                        "(objectClass=builtinDomain)"
+                                        "(objectClass=samba4LocalDomain)))",
+                                ldap_encode_ndr_dom_sid(ac, ac->domain_sid));
+       if (filter == NULL) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       ret = ldb_build_search_req(&req, ac->module->ldb, ac,
+                                  ldb_get_default_basedn(ac->module->ldb),
+                                  LDB_SCOPE_SUBTREE,
+                                  filter, attrs,
+                                  NULL,
+                                  ac, samldb_get_sid_domain_callback,
+                                  ac->req);
+
+       if (ret != LDB_SUCCESS) {
+               return ret;
+       }
+
+       ac->next_rid = 0;
+       return ldb_next_request(ac->module, req);
 }
 
-static int samldb_fill_group_object(struct ldb_module *module, const struct ldb_message *msg,
-                                                   struct ldb_message **ret_msg)
+static bool samldb_msg_add_sid(struct ldb_message *msg,
+                               const char *name,
+                               const struct dom_sid *sid)
 {
-       int ret;
-       unsigned int group_type;
-       char *name;
-       struct ldb_message *msg2;
-       struct ldb_dn *dom_dn;
-       const char *rdn_name;
-       TALLOC_CTX *mem_ctx = talloc_new(msg);
-       const char *errstr;
-       if (!mem_ctx) {
+       struct ldb_val v;
+       enum ndr_err_code ndr_err;
+
+       ndr_err = ndr_push_struct_blob(&v, msg, NULL, sid,
+                                      (ndr_push_flags_fn_t)ndr_push_dom_sid);
+       if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
+               return false;
+       }
+       return (ldb_msg_add_value(msg, name, &v, NULL) == 0);
+}
+
+static int samldb_new_sid(struct samldb_ctx *ac)
+{
+
+       if (ac->domain_sid == NULL || ac->next_rid == 0) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       /* build the new msg */
-       msg2 = ldb_msg_copy(mem_ctx, msg);
-       if (!msg2) {
-               ldb_debug(module->ldb, LDB_DEBUG_FATAL, "samldb_fill_group_object: ldb_msg_copy failed!\n");
-               talloc_free(mem_ctx);
+       ac->sid = dom_sid_add_rid(ac, ac->domain_sid, ac->next_rid + 1);
+       if (ac->sid == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       ret = samdb_copy_template(module->ldb, msg2, 
-                                 "group",
-                                 &errstr);
-       if (ret != 0) {
-               
-               talloc_free(mem_ctx);
-               return ret;
+       if ( ! samldb_msg_add_sid(ac->msg, "objectSid", ac->sid)) {
+               return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       rdn_name = ldb_dn_get_rdn_name(msg2->dn);
+       return samldb_next_step(ac);
+}
 
-       if (strcasecmp(rdn_name, "cn") != 0) {
-               ldb_debug(module->ldb, LDB_DEBUG_FATAL, "samldb_fill_group_object: Bad RDN (%s) for group!\n", rdn_name);
-               talloc_free(mem_ctx);
-               return LDB_ERR_CONSTRAINT_VIOLATION;
+static int samldb_check_sid_callback(struct ldb_request *req,
+                                    struct ldb_reply *ares)
+{
+       struct samldb_ctx *ac;
+       int ret;
+
+       ac = talloc_get_type(req->context, struct samldb_ctx);
+
+       if (!ares) {
+               ret = LDB_ERR_OPERATIONS_ERROR;
+               goto done;
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
        }
 
-       ret = samdb_search_for_parent_domain(module->ldb, mem_ctx, msg2->dn, &dom_dn, &errstr);
+       switch (ares->type) {
+       case LDB_REPLY_ENTRY:
+
+               /* if we get an entry it means an object with the
+                * requested sid exists */
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_CONSTRAINT_VIOLATION);
+
+       case LDB_REPLY_REFERRAL:
+               /* ignore */
+               talloc_free(ares);
+               break;
+
+       case LDB_REPLY_DONE:
+
+               /* not found, go on */
+               talloc_free(ares);
+               ret = samldb_next_step(ac);
+               break;
+       }
+
+done:
+       if (ret != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, NULL, NULL, ret);
+       }
+
+       return LDB_SUCCESS;
+}
+
+static int samldb_check_sid(struct samldb_ctx *ac)
+{
+       const char *const attrs[2] = { "objectSid", NULL };
+       struct ldb_request *req;
+       char *filter;
+       int ret;
+
+       if (ac->sid == NULL) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       filter = talloc_asprintf(ac, "(objectSid=%s)",
+                                ldap_encode_ndr_dom_sid(ac, ac->sid));
+       if (filter == NULL) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       ret = ldb_build_search_req(&req, ac->module->ldb, ac,
+                                  ldb_get_default_basedn(ac->module->ldb),
+                                  LDB_SCOPE_SUBTREE,
+                                  filter, attrs,
+                                  NULL,
+                                  ac, samldb_check_sid_callback,
+                                  ac->req);
+
        if (ret != LDB_SUCCESS) {
-               ldb_asprintf_errstring(module->ldb,
-                                      "samldb_fill_group_object: %s", errstr);
                return ret;
        }
 
-       /* Generate a random name, if no samAccountName was supplied */
-       if (ldb_msg_find_element(msg2, "samAccountName") == NULL) {
-               ret = samldb_generate_samAccountName(module, mem_ctx, dom_dn, &name);
-               if (ret != LDB_SUCCESS) {
-                       talloc_free(mem_ctx);
-                       return ret;
-               }
-               ret = samdb_find_or_add_attribute(module->ldb, msg2, "sAMAccountName", name);
-               if (ret) {
-                       talloc_free(mem_ctx);
-                       return ret;
-               }
+       return ldb_next_request(ac->module, req);
+}
+
+static int samldb_notice_sid_callback(struct ldb_request *req,
+                                       struct ldb_reply *ares)
+{
+       struct samldb_ctx *ac;
+       int ret;
+
+       ac = talloc_get_type(req->context, struct samldb_ctx);
+
+       if (!ares) {
+               ret = LDB_ERR_OPERATIONS_ERROR;
+               goto done;
        }
-       
-       if (ldb_msg_find_element(msg2, "sAMAccountType") != NULL) {
-               ldb_asprintf_errstring(module->ldb, "sAMAccountType must not be specified");
-               talloc_free(mem_ctx);
-               return LDB_ERR_UNWILLING_TO_PERFORM;
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
        }
-       group_type = samdb_result_uint(msg2, "groupType", 0);
-       if (group_type == 0) {
-               ldb_asprintf_errstring(module->ldb, "groupType invalid");
-               talloc_free(mem_ctx);
-               return LDB_ERR_UNWILLING_TO_PERFORM;
-       } else {
-               unsigned int account_type = samdb_gtype2atype(group_type);
-               ret = samdb_msg_add_uint(module->ldb, msg2, msg2,
-                                        "sAMAccountType",
-                                        account_type);
-               if (ret != LDB_SUCCESS) {
-                       return ret;
-               }
+       if (ares->type != LDB_REPLY_DONE) {
+               ldb_set_errstring(ac->module->ldb,
+                       "Invalid reply type!\n");
+               ret = LDB_ERR_OPERATIONS_ERROR;
+               goto done;
        }
 
-       /* Manage SID allocation, conflicts etc */
-       ret = samldb_handle_sid(module, mem_ctx, msg2, dom_dn); 
+       ret = samldb_next_step(ac);
 
-       if (ret == LDB_SUCCESS) {
-               talloc_steal(msg, msg2);
-               *ret_msg = msg2;
+done:
+       if (ret != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, NULL, NULL, ret);
        }
-       talloc_free(mem_ctx);
-       return ret;
+
+       return LDB_SUCCESS;
 }
 
-static int samldb_fill_user_or_computer_object(struct ldb_module *module, const struct ldb_message *msg, struct ldb_message **ret_msg)
+/* If we are adding new users/groups, we need to update the nextRid
+ * attribute to be 'above' the new/incoming RID. Attempt to do it
+ *atomically. */
+static int samldb_notice_sid(struct samldb_ctx *ac)
 {
+       uint32_t old_id, new_id;
+       struct ldb_request *req;
+       struct ldb_message *msg;
+       struct ldb_message_element *els;
+       struct ldb_val *vals;
        int ret;
-       char *name;
-       struct ldb_message *msg2;
-       struct ldb_dn *dom_dn;
-       const char *rdn_name;
-       TALLOC_CTX *mem_ctx = talloc_new(msg);
-       const char *errstr;
-       unsigned int user_account_control;
-       if (!mem_ctx) {
+
+       old_id = ac->next_rid;
+       new_id = ac->sid->sub_auths[ac->sid->num_auths - 1];
+
+       if (old_id >= new_id) {
+               /* no need to update the domain nextRid attribute */
+               return samldb_next_step(ac);
+       }
+
+       /* we do a delete and add as a single operation. That prevents
+          a race, in case we are not actually on a transaction db */
+       msg = talloc_zero(ac, struct ldb_message);
+       if (msg == NULL) {
+               ldb_oom(ac->module->ldb);
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+       els = talloc_array(msg, struct ldb_message_element, 2);
+       if (els == NULL) {
+               ldb_oom(ac->module->ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
+       vals = talloc_array(msg, struct ldb_val, 2);
+       if (vals == NULL) {
+               ldb_oom(ac->module->ldb);
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+       msg->dn = ac->domain_dn;
+       msg->num_elements = 2;
+       msg->elements = els;
 
-       /* build the new msg */
-       msg2 = ldb_msg_copy(mem_ctx, msg);
-       if (!msg2) {
-               ldb_debug(module->ldb, LDB_DEBUG_FATAL, "samldb_fill_user_or_computer_object: ldb_msg_copy failed!\n");
-               talloc_free(mem_ctx);
+       els[0].num_values = 1;
+       els[0].values = &vals[0];
+       els[0].flags = LDB_FLAG_MOD_DELETE;
+       els[0].name = talloc_strdup(msg, "nextRid");
+       if (!els[0].name) {
+               ldb_oom(ac->module->ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       ret = samdb_copy_template(module->ldb, msg2, 
-                                 "user",
-                                 &errstr);
-       if (ret) {
-               ldb_asprintf_errstring(module->ldb, 
-                                      "samldb_fill_user_or_computer_object: Error copying user template: %s\n",
-                                      errstr);
-               talloc_free(mem_ctx);
+       els[1].num_values = 1;
+       els[1].values = &vals[1];
+       els[1].flags = LDB_FLAG_MOD_ADD;
+       els[1].name = els[0].name;
+
+       vals[0].data = (uint8_t *)talloc_asprintf(vals, "%u", old_id);
+       if (!vals[0].data) {
+               ldb_oom(ac->module->ldb);
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+       vals[0].length = strlen((char *)vals[0].data);
+
+       vals[1].data = (uint8_t *)talloc_asprintf(vals, "%u", new_id);
+       if (!vals[1].data) {
+               ldb_oom(ac->module->ldb);
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+       vals[1].length = strlen((char *)vals[1].data);
+
+       ret = ldb_build_mod_req(&req, ac->module->ldb, ac,
+                               msg, NULL,
+                               ac, samldb_notice_sid_callback,
+                               ac->req);
+       if (ret != LDB_SUCCESS) {
                return ret;
        }
 
-       rdn_name = ldb_dn_get_rdn_name(msg2->dn);
+       return ldb_next_request(ac->module, req);
+}
 
-       if (strcasecmp(rdn_name, "cn") != 0) {
-               ldb_asprintf_errstring(module->ldb, "Bad RDN (%s=) for user/computer, should be CN=!\n", rdn_name);
-               talloc_free(mem_ctx);
-               return LDB_ERR_CONSTRAINT_VIOLATION;
+static int samldb_add_entry_callback(struct ldb_request *req,
+                                       struct ldb_reply *ares)
+{
+       struct samldb_ctx *ac;
+
+       ac = talloc_get_type(req->context, struct samldb_ctx);
+
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
+       if (ares->type != LDB_REPLY_DONE) {
+               ldb_set_errstring(ac->module->ldb,
+                       "Invalid reply type!\n");
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
        }
 
-       ret = samdb_search_for_parent_domain(module->ldb, mem_ctx, msg2->dn, &dom_dn, &errstr);
+       /* we exit the samldb module here */
+       return ldb_module_done(ac->req, ares->controls,
+                               ares->response, LDB_SUCCESS);
+}
+
+static int samldb_add_entry(struct samldb_ctx *ac)
+{
+       struct ldb_request *req;
+       int ret;
+
+       ret = ldb_build_add_req(&req, ac->module->ldb, ac,
+                               ac->msg,
+                               ac->req->controls,
+                               ac, samldb_add_entry_callback,
+                               ac->req);
        if (ret != LDB_SUCCESS) {
-               ldb_asprintf_errstring(module->ldb,
-                                      "samldb_fill_user_or_computer_object: %s", errstr);
                return ret;
        }
 
-       if (ldb_msg_find_element(msg2, "samAccountName") == NULL) {
-               ret = samldb_generate_samAccountName(module, mem_ctx, dom_dn, &name);
-               if (ret != LDB_SUCCESS) {
-                       talloc_free(mem_ctx);
-                       return ret;
-               }
-               ret = samdb_find_or_add_attribute(module->ldb, msg2, "sAMAccountName", name);
-               if (ret) {
-                       talloc_free(mem_ctx);
-                       return ret;
-               }
+       return ldb_next_request(ac->module, req);
+}
+
+static int samldb_fill_object(struct samldb_ctx *ac, const char *type)
+{
+       int ret;
+
+       /* first look for the template */
+       ac->type = type;
+       ret = samldb_add_step(ac, samldb_search_template);
+       if (ret != LDB_SUCCESS) return ret;
+
+       /* then apply it */
+       ret = samldb_add_step(ac, samldb_apply_template);
+       if (ret != LDB_SUCCESS) return ret;
+
+       /* search for a parent domain objet */
+       ac->check_dn = ac->req->op.add.message->dn;
+       ret = samldb_add_step(ac, samldb_get_parent_domain);
+       if (ret != LDB_SUCCESS) return ret;
+
+       /* check if we have a valid samAccountName */
+       ret = samldb_add_step(ac, samldb_check_samAccountName);
+       if (ret != LDB_SUCCESS) return ret;
+
+       /* check account_type/group_type */
+       ret = samldb_add_step(ac, samldb_check_samAccountType);
+       if (ret != LDB_SUCCESS) return ret;
+
+       /* check if we have a valid SID */
+       ac->sid = samdb_result_dom_sid(ac, ac->msg, "objectSid");
+       if ( ! ac->sid) {
+               ret = samldb_add_step(ac, samldb_new_sid);
+               if (ret != LDB_SUCCESS) return ret;
+       } else {
+               ret = samldb_add_step(ac, samldb_get_sid_domain);
+               if (ret != LDB_SUCCESS) return ret;
        }
 
-       if (ldb_msg_find_element(msg2, "sAMAccountType") != NULL) {
-               ldb_asprintf_errstring(module->ldb, "sAMAccountType must not be specified");
-               talloc_free(mem_ctx);
-               return LDB_ERR_UNWILLING_TO_PERFORM;
+       ret = samldb_add_step(ac, samldb_check_sid);
+       if (ret != LDB_SUCCESS) return ret;
+
+       ret = samldb_add_step(ac, samldb_notice_sid);
+       if (ret != LDB_SUCCESS) return ret;
+
+       /* finally proceed with adding the entry */
+       ret = samldb_add_step(ac, samldb_add_entry);
+       if (ret != LDB_SUCCESS) return ret;
+
+       return samldb_first_step(ac);
+
+       /* TODO: userAccountControl, badPwdCount, codePage,
+        *       countryCode, badPasswordTime, lastLogoff, lastLogon,
+        *       pwdLastSet, primaryGroupID, accountExpires, logonCount */
+
+}
+
+static int samldb_foreign_notice_sid_callback(struct ldb_request *req,
+                                               struct ldb_reply *ares)
+{
+       struct samldb_ctx *ac;
+       const char *nextRid;
+       const char *name;
+       int ret;
+
+       ac = talloc_get_type(req->context, struct samldb_ctx);
+
+       if (!ares) {
+               ret = LDB_ERR_OPERATIONS_ERROR;
+               goto done;
        }
-       user_account_control = samdb_result_uint(msg2, "userAccountControl", 0);
-       if (user_account_control == 0) {
-               ldb_asprintf_errstring(module->ldb, "userAccountControl invalid");
-               talloc_free(mem_ctx);
-               return LDB_ERR_UNWILLING_TO_PERFORM;
-       } else {
-               unsigned int account_type = samdb_uf2atype(user_account_control);
-               ret = samdb_msg_add_uint(module->ldb, msg2, msg2,
-                                        "sAMAccountType",
-                                        account_type);
-               if (ret != LDB_SUCCESS) {
-                       return ret;
-               }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
        }
 
-       /* Manage SID allocation, conflicts etc */
-       ret = samldb_handle_sid(module, mem_ctx, msg2, dom_dn); 
+       switch (ares->type) {
+       case LDB_REPLY_ENTRY:
+               /* save entry */
+               if (ac->next_rid != 0) {
+                       /* one too many! */
+                       ldb_set_errstring(ac->module->ldb,
+                               "Invalid number of results while searching "
+                               "for domain object");
+                       ret = LDB_ERR_OPERATIONS_ERROR;
+                       break;
+               }
 
-       /* TODO: userAccountControl, badPwdCount, codePage, countryCode, badPasswordTime, lastLogoff, lastLogon, pwdLastSet, primaryGroupID, accountExpires, logonCount */
+               nextRid = ldb_msg_find_attr_as_string(ares->message,
+                                                       "nextRid", NULL);
+               if (nextRid == NULL) {
+                       ldb_asprintf_errstring(ac->module->ldb,
+                               "attribute nextRid not found in %s\n",
+                               ldb_dn_get_linearized(ares->message->dn));
+                       ret = LDB_ERR_OPERATIONS_ERROR;
+                       break;
+               }
+
+               ac->next_rid = strtol(nextRid, NULL, 0);
+
+               ac->domain_dn = talloc_steal(ac, ares->message->dn);
+
+               name = samdb_result_string(ares->message, "name", NULL);
+               ldb_debug(ac->module->ldb, LDB_DEBUG_TRACE,
+                        "NOTE (strange but valid): Adding foreign SID "
+                        "record with SID %s, but this domain (%s) is "
+                        "not foreign in the database",
+                        dom_sid_string(ares, ac->sid), name);
 
-       if (ret == 0) {
-               *ret_msg = msg2;
-               talloc_steal(msg, msg2);
+               talloc_free(ares);
+               break;
+
+       case LDB_REPLY_REFERRAL:
+               /* ignore */
+               talloc_free(ares);
+               break;
+
+       case LDB_REPLY_DONE:
+
+               /* if this is a fake foreign SID, notice the SID */
+               if (ac->domain_dn) {
+                       ret = samldb_notice_sid(ac);
+                       break;
+               }
+
+               /* found, go on */
+               ret = samldb_next_step(ac);
+               break;
+       }
+
+done:
+       if (ret != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, NULL, NULL, ret);
        }
-       talloc_free(mem_ctx);
-       return ret;
+
+       return LDB_SUCCESS;
 }
-       
-static int samldb_fill_foreignSecurityPrincipal_object(struct ldb_module *module, const struct ldb_message *msg, 
-                                                      struct ldb_message **ret_msg)
+
+/* Find a domain object in the parents of a particular DN. */
+static int samldb_foreign_notice_sid(struct samldb_ctx *ac)
 {
-       struct ldb_message *msg2;
-       const char *rdn_name;
-       struct dom_sid *dom_sid;
-       struct dom_sid *sid;
-       const char *dom_attrs[] = { "name", NULL };
-       struct ldb_message **dom_msgs;
-       const char *errstr;
+       static const char * const attrs[3] = { "nextRid", "name", NULL };
+       struct ldb_request *req;
+       char *filter;
        int ret;
 
-       TALLOC_CTX *mem_ctx = talloc_new(msg);
-       if (!mem_ctx) {
+       if (ac->sid == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       /* build the new msg */
-       msg2 = ldb_msg_copy(mem_ctx, msg);
-       if (!msg2) {
-               ldb_debug(module->ldb, LDB_DEBUG_FATAL, "samldb_fill_foreignSecurityPrincipal_object: ldb_msg_copy failed!\n");
-               talloc_free(mem_ctx);
+       ac->domain_sid = dom_sid_dup(ac, ac->sid);
+       if (!ac->domain_sid) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
+       /* get the domain component part of the provided SID */
+       ac->domain_sid->num_auths--;
 
-       ret = samdb_copy_template(module->ldb, msg2, 
-                                 "ForeignSecurityPrincipal",
-                                 &errstr);
-       if (ret != 0) {
-               ldb_asprintf_errstring(module->ldb, 
-                                      "samldb_fill_foreignSecurityPrincipal_object: "
-                                      "Error copying template: %s",
-                                   errstr);
-               talloc_free(mem_ctx);
-               return ret;
+       filter = talloc_asprintf(ac, "(&(objectSid=%s)(objectclass=domain))",
+                                ldap_encode_ndr_dom_sid(ac, ac->domain_sid));
+       if (filter == NULL) {
+               return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       rdn_name = ldb_dn_get_rdn_name(msg2->dn);
+       ret = ldb_build_search_req(&req, ac->module->ldb, ac,
+                                  ldb_get_default_basedn(ac->module->ldb),
+                                  LDB_SCOPE_SUBTREE,
+                                  filter, attrs,
+                                  NULL,
+                                  ac, samldb_foreign_notice_sid_callback,
+                                  ac->req);
 
-       if (strcasecmp(rdn_name, "cn") != 0) {
-               ldb_asprintf_errstring(module->ldb, "Bad RDN (%s=) for ForeignSecurityPrincipal, should be CN=!", rdn_name);
-               talloc_free(mem_ctx);
-               return LDB_ERR_CONSTRAINT_VIOLATION;
+       if (ret != LDB_SUCCESS) {
+               return ret;
        }
 
-       sid = samdb_result_dom_sid(msg2, msg, "objectSid");
-       if (!sid) {
-               /* Slightly different for the foreign sids.  We don't want
-                * domain SIDs ending up there, it would cause all sorts of
-                * pain */
-
-               sid = dom_sid_parse_talloc(msg2, (const char *)ldb_dn_get_rdn_val(msg2->dn)->data);
-               if (!sid) {
-                       ldb_set_errstring(module->ldb, "No valid found SID in ForeignSecurityPrincipal CN!");
-                       talloc_free(mem_ctx);
-                       return LDB_ERR_CONSTRAINT_VIOLATION;
-               }
+       ac->next_rid = 0;
+       return ldb_next_request(ac->module, req);
+}
 
-               if ( ! samldb_msg_add_sid(module, msg2, "objectSid", sid)) {
-                       talloc_free(sid);
-                       return LDB_ERR_OPERATIONS_ERROR;
-               }
+static int samldb_fill_foreignSecurityPrincipal_object(struct samldb_ctx *ac)
+{
+       int ret;
 
-               dom_sid = dom_sid_dup(mem_ctx, sid);
-               if (!dom_sid) {
-                       talloc_free(mem_ctx);
-                       return LDB_ERR_OPERATIONS_ERROR;
+       ac->sid = samdb_result_dom_sid(ac->msg, ac->msg, "objectSid");
+       if (ac->sid == NULL) {
+               ac->sid = dom_sid_parse_talloc(ac->msg,
+                          (const char *)ldb_dn_get_rdn_val(ac->msg->dn)->data);
+               if (!ac->sid) {
+                       ldb_set_errstring(ac->module->ldb,
+                                       "No valid found SID in "
+                                       "ForeignSecurityPrincipal CN!");
+                       talloc_free(ac);
+                       return LDB_ERR_CONSTRAINT_VIOLATION;
                }
-               /* get the domain component part of the provided SID */
-               dom_sid->num_auths--;
-
-               /* find the domain DN */
-
-               ret = gendb_search(module->ldb,
-                                  mem_ctx, NULL, &dom_msgs, dom_attrs,
-                                  "(&(objectSid=%s)(objectclass=domain))",
-                                  ldap_encode_ndr_dom_sid(mem_ctx, dom_sid));
-               if (ret >= 1) {
-                       /* We don't really like the idea of foreign sids that are not foreign, but it happens */
-                       const char *name = samdb_result_string(dom_msgs[0], "name", NULL);
-                       ldb_debug(module->ldb, LDB_DEBUG_TRACE, "NOTE (strange but valid): Adding foreign SID record with SID %s, but this domian (%s) is already in the database", 
-                                 dom_sid_string(mem_ctx, sid), name); 
-               } else if (ret == -1) {
-                       ldb_asprintf_errstring(module->ldb,
-                                               "samldb_fill_foreignSecurityPrincipal_object: error searching for a domain with this sid: %s\n", 
-                                               dom_sid_string(mem_ctx, dom_sid));
-                       talloc_free(dom_msgs);
+               if ( ! samldb_msg_add_sid(ac->msg, "objectSid", ac->sid)) {
+                       talloc_free(ac);
                        return LDB_ERR_OPERATIONS_ERROR;
                }
        }
 
-       /* This isn't an operation on a domain we know about, so just
-        * check for the SID, looking for duplicates via the common
-        * code */
-       ret = samldb_notice_sid(module, msg2, sid);
-       if (ret == 0) {
-               talloc_steal(msg, msg2);
-               *ret_msg = msg2;
-       }
-       
-       return ret;
+       /* first look for the template */
+       ac->type = "foreignSecurityPrincipal";
+       ret = samldb_add_step(ac, samldb_search_template);
+       if (ret != LDB_SUCCESS) return ret;
+
+       /* then apply it */
+       ret = samldb_add_step(ac, samldb_apply_template);
+       if (ret != LDB_SUCCESS) return ret;
+
+       /* check we do not already have this SID */
+       ret = samldb_add_step(ac, samldb_check_sid);
+       if (ret != LDB_SUCCESS) return ret;
+
+       /* check if we need to notice this SID */
+       ret = samldb_add_step(ac, samldb_foreign_notice_sid);
+       if (ret != LDB_SUCCESS) return ret;
+
+       /* finally proceed with adding the entry */
+       ret = samldb_add_step(ac, samldb_add_entry);
+       if (ret != LDB_SUCCESS) return ret;
+
+       return samldb_first_step(ac);
 }
 
-/* add_record */
+static int samldb_check_rdn(struct ldb_module *module, struct ldb_dn *dn)
+{
+       const char *rdn_name;
 
-/*
- * FIXME
- *
- * Actually this module is not async at all as it does a number of sync searches
- * in the process. It still to be decided how to deal with it properly so it is
- * left SYNC for now until we think of a good solution.
- */
+       rdn_name = ldb_dn_get_rdn_name(dn);
+
+       if (strcasecmp(rdn_name, "cn") != 0) {
+               ldb_asprintf_errstring(module->ldb,
+                                       "Bad RDN (%s=) for samldb object, "
+                                       "should be CN=!\n", rdn_name);
+               return LDB_ERR_CONSTRAINT_VIOLATION;
+       }
 
+       return LDB_SUCCESS;
+}
+
+/* add_record */
 static int samldb_add(struct ldb_module *module, struct ldb_request *req)
 {
-       const struct ldb_message *msg = req->op.add.message;
-       struct ldb_message *msg2 = NULL;
-       struct ldb_request *down_req;
+       struct samldb_ctx *ac;
        int ret;
 
        ldb_debug(module->ldb, LDB_DEBUG_TRACE, "samldb_add_record\n");
 
-       if (ldb_dn_is_special(msg->dn)) { /* do not manipulate our control entries */
+       /* do not manipulate our control entries */
+       if (ldb_dn_is_special(req->op.add.message->dn)) {
                return ldb_next_request(module, req);
        }
 
-       /* is user or computer? */
-       if ((samdb_find_attribute(module->ldb, msg, "objectclass", "user") != NULL) || 
-           (samdb_find_attribute(module->ldb, msg, "objectclass", "computer") != NULL)) {
-               /*  add all relevant missing objects */
-               ret = samldb_fill_user_or_computer_object(module, msg, &msg2);
-               if (ret) {
-                       return ret;
-               }
+       ac = samldb_ctx_init(module, req);
+       if (ac == NULL) {
+               return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       /* is group? add all relevant missing objects */
-       if ( ! msg2 ) {
-               if (samdb_find_attribute(module->ldb, msg, "objectclass", "group") != NULL) {
-                       ret = samldb_fill_group_object(module, msg, &msg2);
-                       if (ret) {
-                               return ret;
-                       }
-               }
+       /* build the new msg */
+       ac->msg = ldb_msg_copy(ac, ac->req->op.add.message);
+       if (!ac->msg) {
+               talloc_free(ac);
+               ldb_debug(ac->module->ldb, LDB_DEBUG_FATAL,
+                         "samldb_add: ldb_msg_copy failed!\n");
+               return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       /* perhaps a foreignSecurityPrincipal? */
-       if ( ! msg2 ) {
-               if (samdb_find_attribute(module->ldb, msg, "objectclass", "foreignSecurityPrincipal") != NULL) {
-                       ret = samldb_fill_foreignSecurityPrincipal_object(module, msg, &msg2);
-                       if (ret) {
-                               return ret;
-                       }
+       if (samdb_find_attribute(module->ldb, ac->msg,
+                                "objectclass", "computer") != NULL) {
+
+               /* make sure the computer object also has the 'user'
+                * objectclass so it will be handled by the next call */
+               ret = samdb_find_or_add_value(module->ldb, ac->msg,
+                                               "objectclass", "user");
+               if (ret != LDB_SUCCESS) {
+                       talloc_free(ac);
+                       return ret;
                }
        }
 
-       if (msg2 == NULL) {
-               return ldb_next_request(module, req);
-       }
+       if (samdb_find_attribute(module->ldb, ac->msg,
+                                "objectclass", "user") != NULL) {
 
-       down_req = talloc(req, struct ldb_request);
-       if (down_req == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
+               ret = samldb_check_rdn(module, ac->req->op.add.message->dn);
+               if (ret != LDB_SUCCESS) {
+                       talloc_free(ac);
+                       return ret;
+               }
+
+               return samldb_fill_object(ac, "user");
        }
 
-       *down_req = *req;
-       
-       down_req->op.add.message = talloc_steal(down_req, msg2);
+       if (samdb_find_attribute(module->ldb, ac->msg,
+                                "objectclass", "group") != NULL) {
+
+               ret = samldb_check_rdn(module, ac->req->op.add.message->dn);
+               if (ret != LDB_SUCCESS) {
+                       talloc_free(ac);
+                       return ret;
+               }
 
-       ldb_set_timeout_from_prev_req(module->ldb, req, down_req);
+               return samldb_fill_object(ac, "group");
+       }
 
-       /* go on with the call chain */
-       ret = ldb_next_request(module, down_req);
+       /* perhaps a foreignSecurityPrincipal? */
+       if (samdb_find_attribute(module->ldb, ac->msg,
+                                "objectclass",
+                                "foreignSecurityPrincipal") != NULL) {
 
-       /* do not free down_req as the call results may be linked to it,
-        * it will be freed when the upper level request get freed */
-       if (ret == LDB_SUCCESS) {
-               req->handle = down_req->handle;
+               ret = samldb_check_rdn(module, ac->req->op.add.message->dn);
+               if (ret != LDB_SUCCESS) {
+                       talloc_free(ac);
+                       return ret;
+               }
+
+               return samldb_fill_foreignSecurityPrincipal_object(ac);
        }
 
-       return ret;
+       talloc_free(ac);
+
+       /* nothing matched, go on */
+       return ldb_next_request(module, req);
 }
 
 /* modify */
@@ -777,6 +1315,8 @@ static int samldb_modify(struct ldb_module *module, struct ldb_request *req)
                return LDB_ERR_UNWILLING_TO_PERFORM;
        }
 
+       /* TODO: do not modify original request, create a new one */
+
        el = ldb_msg_find_element(req->op.mod.message, "groupType");
        if (el && el->flags & (LDB_FLAG_MOD_ADD|LDB_FLAG_MOD_REPLACE) && el->num_values == 1) {
                req->op.mod.message = msg = ldb_msg_copy_shallow(req, req->op.mod.message);
index 968b19c038d5254054b5d32cf202836fc6dadc0a..56d24a2962859ada27aa34c4a3f233b3c9a25b8a 100644 (file)
@@ -62,8 +62,10 @@ struct schema_fsmo_private_data {
 };
 
 struct schema_fsmo_search_data {
-       struct schema_fsmo_private_data *module_context;
-       struct ldb_request *orig_req;
+       struct ldb_module *module;
+       struct ldb_request *req;
+
+       const struct dsdb_schema *schema;
 };
 
 static int schema_fsmo_init(struct ldb_module *module)
@@ -152,6 +154,16 @@ static int schema_fsmo_add(struct ldb_module *module, struct ldb_request *req)
        uint32_t id32;
        WERROR status;
 
+       /* special objects should always go through */
+       if (ldb_dn_is_special(req->op.add.message->dn)) {
+               return ldb_next_request(module, req);
+       }
+
+       /* replicated update should always go through */
+       if (ldb_request_get_control(req, DSDB_CONTROL_REPLICATED_UPDATE_OID)) {
+               return ldb_next_request(module, req);
+       }
+
        schema = dsdb_get_schema(module->ldb);
        if (!schema) {
                return ldb_next_request(module, req);
@@ -315,41 +327,54 @@ static int generate_dITContentRules(struct ldb_context *ldb, struct ldb_message
 /* Add objectClasses, attributeTypes and dITContentRules from the
    schema object (they are not stored in the database)
  */
-static int schema_fsmo_search_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares) 
+static int schema_fsmo_search_callback(struct ldb_request *req, struct ldb_reply *ares)
 {
-       const struct dsdb_schema *schema = dsdb_get_schema(ldb);
-       struct schema_fsmo_search_data *search_data = talloc_get_type(context, struct schema_fsmo_search_data);
-       struct ldb_request *orig_req = search_data->orig_req;
-       TALLOC_CTX *mem_ctx;
+       struct schema_fsmo_search_data *ac;
+       struct schema_fsmo_private_data *mc;
        int i, ret;
 
-       /* Only entries are interesting, and we handle the case of the parent seperatly */
-       if (ares->type != LDB_REPLY_ENTRY) {
-               return orig_req->callback(ldb, orig_req->context, ares);
-       }
+       ac = talloc_get_type(req->context, struct schema_fsmo_search_data);
+       mc = talloc_get_type(ac->module->private_data, struct schema_fsmo_private_data);
 
-       if (ldb_dn_compare(ares->message->dn, search_data->module_context->aggregate_dn) != 0) {
-               talloc_free(mem_ctx);
-               return orig_req->callback(ldb, orig_req->context, ares);
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
        }
-
-       mem_ctx = talloc_new(ares);
-       if (!mem_ctx) {
-               ldb_oom(ldb);
-               return LDB_ERR_OPERATIONS_ERROR;
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
        }
+       /* Only entries are interesting, and we handle the case of the parent seperatly */
 
-       for (i=0; i < ARRAY_SIZE(generated_attrs); i++) {
-               if (ldb_attr_in_list(orig_req->op.search.attrs, generated_attrs[i].attr)) {
-                       ret = generated_attrs[i].fn(ldb, ares->message, schema);
-                       if (ret != LDB_SUCCESS) {
-                               return ret;
+       switch (ares->type) {
+       case LDB_REPLY_ENTRY:
+
+               if (ldb_dn_compare(ares->message->dn, mc->aggregate_dn) != 0) {
+                       return ldb_module_send_entry(ac->req, ares->message);
+               }
+
+               for (i=0; i < ARRAY_SIZE(generated_attrs); i++) {
+                       if (ldb_attr_in_list(ac->req->op.search.attrs, generated_attrs[i].attr)) {
+                               ret = generated_attrs[i].fn(ac->module->ldb, ares->message, ac->schema);
+                               if (ret != LDB_SUCCESS) {
+                                       return ret;
+                               }
                        }
                }
+
+               return ldb_module_send_entry(ac->req, ares->message);
+
+       case LDB_REPLY_REFERRAL:
+
+               return ldb_module_send_referral(ac->req, ares->referral);
+
+       case LDB_REPLY_DONE:
+
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
        }
 
-       talloc_free(mem_ctx);
-       return orig_req->callback(ldb, orig_req->context, ares);
+       return LDB_SUCCESS;
 }
 
 /* search */
@@ -380,27 +405,24 @@ static int schema_fsmo_search(struct ldb_module *module, struct ldb_request *req
                ldb_oom(module->ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       down_req = talloc(req, struct ldb_request);     
-       if (!down_req) {
-               ldb_oom(module->ldb);
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-       
-       *down_req = *req;
-       search_context->orig_req = req;
-       search_context->module_context = talloc_get_type(module->private_data, struct schema_fsmo_private_data);
-       down_req->context = search_context;
 
-       down_req->callback = schema_fsmo_search_callback;
+       search_context->module = module;
+       search_context->req = req;
+       search_context->schema = schema;
 
-       ret = ldb_next_request(module, down_req);
-
-       /* do not free down_req as the call results may be linked to it,
-        * it will be freed when the upper level request get freed */
-       if (ret == LDB_SUCCESS) {
-               req->handle = down_req->handle;
+       ret = ldb_build_search_req_ex(&down_req, module->ldb, search_context,
+                                       req->op.search.base,
+                                       req->op.search.scope,
+                                       req->op.search.tree,
+                                       req->op.search.attrs,
+                                       req->controls,
+                                       search_context, schema_fsmo_search_callback,
+                                       req);
+       if (ret != LDB_SUCCESS) {
+               return LDB_ERR_OPERATIONS_ERROR;
        }
-       return ret;
+
+       return ldb_next_request(module, down_req);
 }
 
 
index 361cf226dc331b1a8a46059213c512552983fb81..0e3b46debee4354131f109c3e75d19f2e53296aa 100644 (file)
@@ -27,7 +27,7 @@
  *
  *  Component: ldb deleted objects control module
  *
- *  Description: this module hides deleted objects, and returns them if the control is there
+ *  Description: this module hides deleted objects, and returns them if the right control is there
  *
  *  Author: Stefan Metzmacher
  */
 struct show_deleted_search_request {
 
        struct ldb_module *module;
-       void *up_context;
-       int (*up_callback)(struct ldb_context *, void *, struct ldb_reply *);
-
-       bool remove_from_msg;
+       struct ldb_request *req;
 };
 
-static int show_deleted_search_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares)
+static int show_deleted_search_callback(struct ldb_request *req,
+                                       struct ldb_reply *ares)
 {
        struct show_deleted_search_request *ar;
 
-       ar = talloc_get_type(context, struct show_deleted_search_request);
+       ar = talloc_get_type(req->context, struct show_deleted_search_request);
 
-       if (ares->type == LDB_REPLY_ENTRY) {
-               bool isDeleted;
+       if (!ares) {
+               return ldb_module_done(ar->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ar->req, ares->controls,
+                                       ares->response, ares->error);
+       }
 
-               isDeleted = ldb_msg_find_attr_as_bool(ares->message, "isDeleted", false);
+       switch (ares->type) {
+       case LDB_REPLY_ENTRY:
 
-               if (isDeleted) {
-                       goto skip_deleted;
-               }
+               return ldb_module_send_entry(ar->req, ares->message);
 
-               if (ar->remove_from_msg) {
-                       ldb_msg_remove_attr(ares->message, "isDeleted");
-               }
-       }
+       case LDB_REPLY_REFERRAL:
+               return ldb_module_send_referral(ar->req, ares->referral);
 
-       return ar->up_callback(ldb, ar->up_context, ares);
+       case LDB_REPLY_DONE:
+               return ldb_module_done(ar->req, ares->controls,
+                                       ares->response, LDB_SUCCESS);
 
-skip_deleted:
-       talloc_free(ares);
+       }
        return LDB_SUCCESS;
 }
 
@@ -81,116 +83,68 @@ static int show_deleted_search(struct ldb_module *module, struct ldb_request *re
        struct ldb_control **saved_controls;
        struct show_deleted_search_request *ar;
        struct ldb_request *down_req;
-       char **new_attrs;
-       uint32_t num_attrs = 0;
-       uint32_t i;
+       char *old_filter;
+       char *new_filter;
        int ret;
 
-       /* check if there's a show deleted control */
-       control = ldb_request_get_control(req, LDB_CONTROL_SHOW_DELETED_OID);
-
-       /* copy the request for modification */
-       down_req = talloc(req, struct ldb_request);
-       if (down_req == NULL) {
-               ldb_oom(module->ldb);
+       ar = talloc_zero(req, struct show_deleted_search_request);
+       if (ar == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
+       ar->module = module;
+       ar->req = req;
 
-       /* copy the request */
-       *down_req = *req;
+       /* check if there's a show deleted control */
+       control = ldb_request_get_control(req, LDB_CONTROL_SHOW_DELETED_OID);
 
-       /* if a control is there remove if from the modified request */
-       if (control && !save_controls(control, down_req, &saved_controls)) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
+       if ( ! control) {
+               old_filter = ldb_filter_from_tree(ar, req->op.search.tree);
+               new_filter = talloc_asprintf(ar, "(&(!(isDeleted=TRUE))%s)",
+                                                old_filter);
 
-       /* if we had a control, then just go on to the next request as we have nothing to hide */
-       if (control) {
-               goto next_request;
-       }
+               ret = ldb_build_search_req(&down_req, module->ldb, ar,
+                                          req->op.search.base,
+                                          req->op.search.scope,
+                                          new_filter,
+                                          req->op.search.attrs,
+                                          req->controls,
+                                          ar, show_deleted_search_callback,
+                                          req);
 
-       ar = talloc(down_req, struct show_deleted_search_request);
-       if (ar == NULL) {
-               ldb_oom(module->ldb);
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       ar->module              = module;
-       ar->up_context          = req->context;
-       ar->up_callback         = req->callback;
-       ar->remove_from_msg     = true;
-
-       /* check if attrs only is specified, in that case check wether we need to modify them */
-       if (down_req->op.search.attrs) {
-               for (i=0; (down_req->op.search.attrs && down_req->op.search.attrs[i]); i++) {
-                       num_attrs++;
-                       if (strcasecmp(down_req->op.search.attrs[i], "*") == 0) {
-                               ar->remove_from_msg = false;
-                       } else if (strcasecmp(down_req->op.search.attrs[i], "isDeleted") == 0) {
-                               ar->remove_from_msg = false;
-                       }
-               }
        } else {
-               ar->remove_from_msg = false;
+               ret = ldb_build_search_req_ex(&down_req, module->ldb, ar,
+                                             req->op.search.base,
+                                             req->op.search.scope,
+                                             req->op.search.tree,
+                                             req->op.search.attrs,
+                                             req->controls,
+                                             ar, show_deleted_search_callback,
+                                             req);
        }
-
-       if (ar->remove_from_msg) {
-               new_attrs = talloc_array(down_req, char *, num_attrs + 2);
-               if (!new_attrs) {
-                       ldb_oom(module->ldb);
-                       return LDB_ERR_OPERATIONS_ERROR;
-               }
-               for (i=0; i < num_attrs; i++) {
-                       new_attrs[i] = discard_const_p(char, down_req->op.search.attrs[i]);             
-               }
-               new_attrs[i] = talloc_strdup(new_attrs, "isDeleted");
-               if (!new_attrs[i]) {
-                       ldb_oom(module->ldb);
-                       return LDB_ERR_OPERATIONS_ERROR;
-               }
-               new_attrs[i+1] = NULL;
-               down_req->op.search.attrs = (const char * const *)new_attrs;
+       if (ret != LDB_SUCCESS) {
+               return ret;
        }
 
-       down_req->context = ar;
-       down_req->callback = show_deleted_search_callback;
-       ldb_set_timeout_from_prev_req(module->ldb, req, down_req);
-
-next_request:
-       /* perform the search */
-       ret = ldb_next_request(module, down_req);
-
-       /* do not free down_req as the call results may be linked to it,
-        * it will be freed when the upper level request get freed */
-       if (ret == LDB_SUCCESS) {
-               req->handle = down_req->handle;
+       /* if a control is there remove if from the modified request */
+       if (control && !save_controls(control, down_req, &saved_controls)) {
+               return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       return ret;
+       /* perform the search */
+       return ldb_next_request(module, down_req);
 }
 
 static int show_deleted_init(struct ldb_module *module)
 {
-       struct ldb_request *req;
        int ret;
 
-       req = talloc(module, struct ldb_request);
-       if (req == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       req->operation = LDB_REQ_REGISTER_CONTROL;
-       req->op.reg_control.oid = LDB_CONTROL_SHOW_DELETED_OID;
-       req->controls = NULL;
-
-       ret = ldb_request(module->ldb, req);
+       ret = ldb_mod_register_control(module, LDB_CONTROL_SHOW_DELETED_OID);
        if (ret != LDB_SUCCESS) {
-               ldb_debug(module->ldb, LDB_DEBUG_ERROR, "show_deleted: Unable to register control with rootdse!\n");
-               talloc_free(req);
+               ldb_debug(module->ldb, LDB_DEBUG_ERROR,
+                       "extended_dn: Unable to register control with rootdse!\n");
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       talloc_free(req);
        return ldb_next_init(module);
 }
 
index 8f9299514551a61af6eb1f4c75bbf8795729813a..d15e85ad41a173b2a7dc966e8195c519e8987e3d 100644 (file)
 #include "librpc/ndr/libndr.h"
 #include "dsdb/samdb/samdb.h"
 
+struct entryuuid_private {
+       struct ldb_context *ldb;
+       struct ldb_dn **base_dns;
+};
+
 static struct ldb_val encode_guid(struct ldb_module *module, TALLOC_CTX *ctx, const struct ldb_val *val)
 {
        struct GUID guid;
@@ -598,10 +603,10 @@ static int nsuniqueid_init(struct ldb_module *module)
        return ldb_next_init(module);
 }
 
-static int get_seq(struct ldb_context *ldb, void *context, 
-                  struct ldb_reply *ares) 
+static int get_seq(struct ldb_request *req,
+                  struct ldb_reply *ares)
 {
-       unsigned long long *seq = (unsigned long long *)context;
+       unsigned long long *seq = (unsigned long long *)req->context;
        if (ares->type == LDB_REPLY_ENTRY) {
                struct ldb_message_element *el = ldb_msg_find_element(ares->message, "contextCSN");
                if (el) {
@@ -609,6 +614,10 @@ static int get_seq(struct ldb_context *ldb, void *context,
                }
        }
 
+       if (ares->type == LDB_REPLY_DONE) {
+               return ldb_request_done(req, LDB_SUCCESS);
+       }
+
        return LDB_SUCCESS;
 }
 
@@ -635,7 +644,7 @@ static int entryuuid_sequence_number(struct ldb_module *module, struct ldb_reque
        partition_ctrl = ldb_request_get_control(req, DSDB_CONTROL_CURRENT_PARTITION_OID);
        if (!partition_ctrl) {
                ldb_debug_set(module->ldb, LDB_DEBUG_FATAL,
-                             "instancetype_add: no current partition control found");
+                             "entryuuid_sequence_number: no current partition control found");
                return LDB_ERR_CONSTRAINT_VIOLATION;
        }
 
@@ -643,39 +652,21 @@ static int entryuuid_sequence_number(struct ldb_module *module, struct ldb_reque
                                    struct dsdb_control_current_partition);
        SMB_ASSERT(partition && partition->version == DSDB_CONTROL_CURRENT_PARTITION_VERSION);
 
-       search_req = talloc(req, struct ldb_request);
-       if (search_req == NULL) {
-               ldb_set_errstring(module->ldb, "Out of Memory");
-               return LDB_ERR_OPERATIONS_ERROR;
+       ret = ldb_build_search_req(&search_req, module->ldb, req,
+                                  partition->dn, LDB_SCOPE_BASE,
+                                  NULL, contextCSN_attr, NULL,
+                                  &seq, get_seq,
+                                  NULL);
+       if (ret != LDB_SUCCESS) {
+               return ret;
        }
-       
-       /* Finally, we have it.  This saves searching over more
-        * partitions than we expose to the client, such as a cn=samba
-        * configuration partition */
 
-       search_req->operation = LDB_SEARCH;
-       search_req->op.search.base = partition->dn;
-       search_req->op.search.scope = LDB_SCOPE_BASE;
-       
-       search_req->op.search.tree = ldb_parse_tree(search_req, "objectClass=*");
-       if (search_req->op.search.tree == NULL) {
-               ldb_set_errstring(module->ldb, "Unable to parse search expression");
-               talloc_free(search_req);
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-       
-       search_req->op.search.attrs = contextCSN_attr;
-       search_req->controls = NULL;
-       search_req->context = &seq;
-       search_req->callback = get_seq;
-       ldb_set_timeout(module->ldb, search_req, 0); /* use default timeout */
-       
        ret = ldb_next_request(module, search_req);
-       
+
        if (ret == LDB_SUCCESS) {
                ret = ldb_wait(search_req->handle, LDB_WAIT_ALL);
        }
-       
+
        talloc_free(search_req);
        if (ret != LDB_SUCCESS) {
                return ret;
index 9c332d2969077eecc786c73880973bae206666d4..10e2dc25ce04363157580de04fcf2d954e6c5eb5 100644 (file)
@@ -3,6 +3,7 @@
 
    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2006-2007
    Copyright (C) Stefan Metzmacher <metze@samba.org> 2007
+   Copyright (C) Simo Sorce <idra@samba.org> 2008
 
    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
 #include "ldb_includes.h"
 
 struct subtree_delete_context {
-       enum sd_step {SD_SEARCH, SD_DO_DEL} step;
-
        struct ldb_module *module;
-       struct ldb_handle *handle;
-       struct ldb_request *orig_req;
-
-       struct ldb_request *search_req;
-       struct ldb_request *down_req;
+       struct ldb_request *req;
 
        int num_children;
 };
 
-static struct subtree_delete_context *subtree_delete_init_handle(struct ldb_request *req, 
-                                                                struct ldb_module *module)
+static struct subtree_delete_context *subdel_ctx_init(struct ldb_module *module,
+                                                     struct ldb_request *req)
 {
        struct subtree_delete_context *ac;
-       struct ldb_handle *h;
-
-       h = talloc_zero(req, struct ldb_handle);
-       if (h == NULL) {
-               ldb_set_errstring(module->ldb, "Out of Memory");
-               return NULL;
-       }
-
-       h->module = module;
 
-       ac = talloc_zero(h, struct subtree_delete_context);
+       ac = talloc_zero(req, struct subtree_delete_context);
        if (ac == NULL) {
-               ldb_set_errstring(module->ldb, "Out of Memory");
-               talloc_free(h);
+               ldb_oom(module->ldb);
                return NULL;
        }
 
-       h->private_data = ac;
-
        ac->module = module;
-       ac->handle = h;
-       ac->orig_req = req;
-
-       req->handle = h;
+       ac->req = req;
 
        return ac;
 }
 
-static int subtree_delete_check_for_children(struct subtree_delete_context *ac)
+static int subtree_delete_search_callback(struct ldb_request *req,
+                                         struct ldb_reply *ares)
 {
-       if (ac->num_children > 0) {
-               ldb_asprintf_errstring(ac->module->ldb, "Cannot delete %s, not a leaf node (has %d children)\n",
-                                      ldb_dn_get_linearized(ac->orig_req->op.del.dn), ac->num_children);
-               return LDB_ERR_NOT_ALLOWED_ON_NON_LEAF;
-       } else {
-               struct ldb_request *req = talloc(ac, struct ldb_request);
-               if (!req) {
-                       ldb_oom(ac->module->ldb);
-                       return LDB_ERR_OPERATIONS_ERROR;
-               }
-               *req = *ac->orig_req;
-               
-               /* Ensure any (io) errors during the search for
-                * children don't propgate back in the error string */
-               ldb_set_errstring(ac->module->ldb, NULL);
+       struct subtree_delete_context *ac;
+       int ret;
 
-               ac->down_req = req;
-               ac->step = SD_DO_DEL;
-               return ldb_next_request(ac->module, req);
-       }
-}
+       ac = talloc_get_type(req->context, struct subtree_delete_context);
 
-static int subtree_delete_search_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares) 
-{
-       struct subtree_delete_context *ac = talloc_get_type(context, struct subtree_delete_context);
-       TALLOC_CTX *mem_ctx = talloc_new(ac);
-    
-       if (!mem_ctx) {
-               ldb_oom(ac->module->ldb);
-               return LDB_ERR_OPERATIONS_ERROR;
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
        }
-       /* OK, we have one of *many* search results here:
 
-          We should also get the entry we tried to rename.  This
-          callback handles this and everything below it.
-        */
+       switch (ares->type) {
+       case LDB_REPLY_ENTRY:
 
-       /* Only entries are interesting, and we handle the case of the parent seperatly */
-       if (ares->type == LDB_REPLY_ENTRY
-           && ldb_dn_compare(ares->message->dn, ac->orig_req->op.del.dn) != 0) {
-               /* And it is an actual entry: now object bitterly that we are not a leaf node */
+               talloc_free(ares);
                ac->num_children++;
+               break;
+
+       case LDB_REPLY_REFERRAL:
+
+               /* ignore */
+               talloc_free(ares);
+               break;
+
+       case LDB_REPLY_DONE:
+
+               if (ac->num_children > 0) {
+                       talloc_free(ares);
+                       ldb_asprintf_errstring(ac->module->ldb,
+                               "Cannot delete %s, not a leaf node "
+                               "(has %d children)\n",
+                               ldb_dn_get_linearized(ac->req->op.del.dn),
+                               ac->num_children);
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                              LDB_ERR_NOT_ALLOWED_ON_NON_LEAF);
+               }
+
+               /* ok no children, let the original request through */
+               ret = ldb_next_request(ac->module, ac->req);
+               if (ret != LDB_SUCCESS) {
+                       return ldb_module_done(ac->req, NULL, NULL, ret);
+               }
+
+               /* free our own context we are not going to be called back */
+               talloc_free(ac);
        }
-       talloc_free(ares);
        return LDB_SUCCESS;
 }
 
-/* rename */
 static int subtree_delete(struct ldb_module *module, struct ldb_request *req)
 {
-       const char *attrs[] = { NULL };
-       struct ldb_request *new_req;
+       static const char * const attrs[2] = { "distinguishedName", NULL };
+       struct ldb_request *search_req;
        struct subtree_delete_context *ac;
        int ret;
        if (ldb_dn_is_special(req->op.rename.olddn)) { /* do not manipulate our control entries */
@@ -142,119 +127,28 @@ static int subtree_delete(struct ldb_module *module, struct ldb_request *req)
           - return an error if there are any
        */
 
-       ac = subtree_delete_init_handle(req, module);
+       ac = subdel_ctx_init(module, req);
        if (!ac) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       ret = ldb_build_search_req(&new_req, module->ldb, req,
-                                  req->op.del.dn, 
-                                  LDB_SCOPE_SUBTREE,
-                                  "(objectClass=*)",
-                                  attrs,
+       /* we do not really need to find all descendents,
+        * if there is even one single direct child, that's
+        * enough to bail out */
+       ret = ldb_build_search_req(&search_req, module->ldb, ac,
+                                  req->op.del.dn, LDB_SCOPE_ONELEVEL,
+                                  "(objectClass=*)", attrs,
                                   req->controls,
-                                  ac, 
-                                  subtree_delete_search_callback);
-
+                                  ac, subtree_delete_search_callback,
+                                  req);
        if (ret != LDB_SUCCESS) {
                return ret;
        }
 
-       ret = ldb_set_timeout_from_prev_req(module->ldb, req, new_req);
-
-       if (ret != LDB_SUCCESS) {
-               return ret;
-       }
-
-       ac->search_req = new_req;
-       if (req == NULL) {
-               ldb_oom(ac->module->ldb);
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-       return ldb_next_request(module, new_req);
-}
-
-
-static int subtree_delete_wait_none(struct ldb_handle *handle) {
-       struct subtree_delete_context *ac;
-       int ret = LDB_ERR_OPERATIONS_ERROR;
-       if (!handle || !handle->private_data) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       if (handle->state == LDB_ASYNC_DONE) {
-               return handle->status;
-       }
-
-       handle->state = LDB_ASYNC_PENDING;
-       handle->status = LDB_SUCCESS;
-
-       ac = talloc_get_type(handle->private_data, struct subtree_delete_context);
-
-       switch (ac->step) {
-       case SD_SEARCH:
-               ret = ldb_wait(ac->search_req->handle, LDB_WAIT_NONE);
-
-               if (ret != LDB_SUCCESS && ret != LDB_ERR_NO_SUCH_OBJECT) {
-                       handle->status = ret;
-                       goto done;
-               }
-               if (ac->search_req->handle->status != LDB_SUCCESS
-                       && ac->search_req->handle->status != LDB_ERR_NO_SUCH_OBJECT) {
-                       handle->status = ac->search_req->handle->status;
-                       goto done;
-               }
-
-               return subtree_delete_check_for_children(ac);
-
-       case SD_DO_DEL:
-               ret = ldb_wait(ac->down_req->handle, LDB_WAIT_NONE);
-
-               if (ret != LDB_SUCCESS) {
-                       handle->status = ret;
-                       goto done;
-               }
-               if (ac->down_req->handle->status != LDB_SUCCESS) {
-                       handle->status = ac->down_req->handle->status;
-                       goto done;
-               }
-
-               if (ac->down_req->handle->state != LDB_ASYNC_DONE) {
-                       return LDB_SUCCESS;
-               }
-
-               break;
-       }
-done:
-       handle->state = LDB_ASYNC_DONE;
-       return ret;
-}
-
-static int subtree_delete_wait_all(struct ldb_handle *handle) {
-
-       int ret;
-
-       while (handle->state != LDB_ASYNC_DONE) {
-               ret = subtree_delete_wait_none(handle);
-               if (ret != LDB_SUCCESS) {
-                       return ret;
-               }
-       }
-
-       return handle->status;
-}
-
-static int subtree_delete_wait(struct ldb_handle *handle, enum ldb_wait_type type)
-{
-       if (type == LDB_WAIT_ALL) {
-               return subtree_delete_wait_all(handle);
-       } else {
-               return subtree_delete_wait_none(handle);
-       }
+       return ldb_next_request(module, search_req);
 }
 
 const struct ldb_module_ops ldb_subtree_delete_module_ops = {
        .name              = "subtree_delete",
        .del               = subtree_delete,
-       .wait              = subtree_delete_wait,
 };
index fd1388d4164bdb4369894fc8501fd7fc6431d473..d3ceb8ad9728753977d84d6764be7747a0ca4b5c 100644 (file)
 
 #include "ldb_includes.h"
 
+struct subren_msg_store {
+       struct subren_msg_store *next;
+       struct ldb_dn *olddn;
+       struct ldb_dn *newdn;
+};
+
 struct subtree_rename_context {
        struct ldb_module *module;
-       struct ldb_handle *handle;
-       struct ldb_request *orig_req;
-
-       struct ldb_request **down_req;
-       int num_requests;
-       int finished_requests;
+       struct ldb_request *req;
 
-       int num_children;
+       struct subren_msg_store *list;
+       struct subren_msg_store *current;
 };
 
-static struct subtree_rename_context *subtree_rename_init_handle(struct ldb_request *req, 
-                                                                struct ldb_module *module)
+static struct subtree_rename_context *subren_ctx_init(struct ldb_module *module,
+                                        struct ldb_request *req)
 {
        struct subtree_rename_context *ac;
-       struct ldb_handle *h;
 
-       h = talloc_zero(req, struct ldb_handle);
-       if (h == NULL) {
-               ldb_set_errstring(module->ldb, "Out of Memory");
+       ac = talloc_zero(req, struct subtree_rename_context);
+       if (ac == NULL) {
+               ldb_oom(module->ldb);
                return NULL;
        }
 
-       h->module = module;
+       ac->module = module;
+       ac->req = req;
 
-       ac = talloc_zero(h, struct subtree_rename_context);
-       if (ac == NULL) {
-               ldb_set_errstring(module->ldb, "Out of Memory");
-               talloc_free(h);
-               return NULL;
+       return ac;
+}
+
+static int subtree_rename_next_request(struct subtree_rename_context *ac);
+
+static int subtree_rename_callback(struct ldb_request *req,
+                                  struct ldb_reply *ares)
+{
+       struct subtree_rename_context *ac;
+       int ret;
+
+       ac = talloc_get_type(req->context, struct subtree_rename_context);
+
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
        }
 
-       h->private_data = ac;
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
 
-       ac->module = module;
-       ac->handle = h;
-       ac->orig_req = req;
+       if (ares->type != LDB_REPLY_DONE) {
+               ldb_set_errstring(ac->module->ldb, "Invalid reply type!\n");
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
 
-       req->handle = h;
+       if (ac->current == NULL) {
+               /* this was the last one */
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, LDB_SUCCESS);
+       }
 
-       return ac;
-}
+       ret = subtree_rename_next_request(ac);
+       if (ret != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, NULL, NULL, ret);
+       }
 
+       talloc_free(ares);
+       return LDB_SUCCESS;
+}
 
-static int subtree_rename_search_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares) 
+static int subtree_rename_next_request(struct subtree_rename_context *ac)
 {
        struct ldb_request *req;
-       struct subtree_rename_context *ac = talloc_get_type(context, struct subtree_rename_context);
-       TALLOC_CTX *mem_ctx = talloc_new(ac);
-    
-       if (!mem_ctx) {
-               ldb_oom(ac->module->ldb);
+       int ret;
+
+       if (ac->current == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       /* OK, we have one of *many* search results here:
-
-          We should also get the entry we tried to rename.  This
-          callback handles this and everything below it.
-        */
-
-       /* Only entries are interesting, and we handle the case of the parent seperatly */
-       if (ares->type == LDB_REPLY_ENTRY
-           && ldb_dn_compare(ares->message->dn, ac->orig_req->op.rename.olddn) != 0) {
-               /* And it is an actual entry: now create a rename from it */
-               int ret;
-
-               struct ldb_dn *newdn = ldb_dn_copy(mem_ctx, ares->message->dn);
-               if (!newdn) {
-                       ldb_oom(ac->module->ldb);
-                       return LDB_ERR_OPERATIONS_ERROR;
+
+       ret = ldb_build_rename_req(&req, ac->module->ldb, ac->current,
+                                  ac->current->olddn,
+                                  ac->current->newdn,
+                                  ac->req->controls,
+                                  ac, subtree_rename_callback,
+                                  ac->req);
+       if (ret != LDB_SUCCESS) {
+               return ret;
+       }
+
+       ac->current = ac->current->next;
+
+       return ldb_next_request(ac->module, req);
+}
+
+static int subtree_rename_search_callback(struct ldb_request *req,
+                                         struct ldb_reply *ares)
+{
+       struct subren_msg_store *store;
+       struct subtree_rename_context *ac;
+       int ret;
+
+       ac = talloc_get_type(req->context, struct subtree_rename_context);
+
+       if (!ares || !ac->current) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
+
+       switch (ares->type) {
+       case LDB_REPLY_ENTRY:
+
+               if (ldb_dn_compare(ares->message->dn, ac->list->olddn) == 0) {
+                       /* this was already stored by the
+                        * subtree_rename_search() */
+                       talloc_free(ares);
+                       return LDB_SUCCESS;
                }
-                       
-               ldb_dn_remove_base_components(newdn, ldb_dn_get_comp_num(ac->orig_req->op.rename.olddn));
 
-               if (!ldb_dn_add_base(newdn, ac->orig_req->op.rename.newdn)) {
-                       ldb_oom(ac->module->ldb);
-                       return LDB_ERR_OPERATIONS_ERROR;
+               store = talloc_zero(ac, struct subren_msg_store);
+               if (store == NULL) {
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
                }
+               ac->current->next = store;
+               ac->current = store;
 
-               ret = ldb_build_rename_req(&req, ldb, mem_ctx,
-                                          ares->message->dn,
-                                          newdn,
-                                          NULL,
-                                          NULL,
-                                          NULL);
-               
-               if (ret != LDB_SUCCESS) {
-                       return ret;
+               /* the first list element contains the base for the rename */
+               store->olddn = talloc_steal(store, ares->message->dn);
+               store->newdn = ldb_dn_copy(store, store->olddn);
+
+               if ( ! ldb_dn_remove_base_components(store->newdn,
+                               ldb_dn_get_comp_num(ac->list->olddn))) {
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
                }
 
-               ret = ldb_set_timeout_from_prev_req(ldb, ac->orig_req, req);
-               
-               if (ret != LDB_SUCCESS) {
-                       return ret;
+               if ( ! ldb_dn_add_base(store->newdn, ac->list->newdn)) {
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
                }
 
-               talloc_steal(req, newdn);
+               break;
 
-               talloc_steal(req, ares->message->dn);
-               
-               talloc_free(ares);
-               
-       } else if (ares->type == LDB_REPLY_DONE) {
-               req = talloc(mem_ctx, struct ldb_request);
-               *req = *ac->orig_req;
-               talloc_free(ares);
+       case LDB_REPLY_REFERRAL:
+               /* ignore */
+               break;
 
-       } else {
-               talloc_free(ares);
-               return LDB_SUCCESS;
-       }
-       
-       ac->down_req = talloc_realloc(ac, ac->down_req, 
-                                     struct ldb_request *, ac->num_requests + 1);
-       if (!ac->down_req) {
-               ldb_oom(ac->module->ldb);
-               return LDB_ERR_OPERATIONS_ERROR;
+       case LDB_REPLY_DONE:
+
+               /* rewind ac->current */
+               ac->current = ac->list;
+
+               /* All dns set up, start with the first one */
+               ret = subtree_rename_next_request(ac);
+
+               if (ret != LDB_SUCCESS) {
+                       return ldb_module_done(ac->req, NULL, NULL, ret);
+               }
+               break;
        }
-       ac->down_req[ac->num_requests] = req;
-       ac->num_requests++;
-       
-       return ldb_next_request(ac->module, req);
-       
+
+       talloc_free(ares);
+       return LDB_SUCCESS;
 }
 
 /* rename */
 static int subtree_rename(struct ldb_module *module, struct ldb_request *req)
 {
-       const char *attrs[] = { NULL };
-       struct ldb_request *new_req;
+       static const char *attrs[2] = { "distinguishedName", NULL };
+       struct ldb_request *search_req;
        struct subtree_rename_context *ac;
        int ret;
        if (ldb_dn_is_special(req->op.rename.olddn)) { /* do not manipulate our control entries */
@@ -176,110 +221,37 @@ static int subtree_rename(struct ldb_module *module, struct ldb_request *req)
           - Regain our sainity 
        */
 
-       ac = subtree_rename_init_handle(req, module);
+       ac = subren_ctx_init(module, req);
        if (!ac) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       ret = ldb_build_search_req(&new_req, module->ldb, req,
+       /* add this entry as the first to do */
+       ac->current = talloc_zero(ac, struct subren_msg_store);
+       if (ac->current == NULL) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+       ac->current->olddn = req->op.rename.olddn;
+       ac->current->newdn = req->op.rename.newdn;
+       ac->list = ac->current;
+
+       ret = ldb_build_search_req(&search_req, module->ldb, ac,
                                   req->op.rename.olddn, 
                                   LDB_SCOPE_SUBTREE,
                                   "(objectClass=*)",
                                   attrs,
-                                  req->controls,
+                                  NULL,
                                   ac, 
-                                  subtree_rename_search_callback);
-
-       if (ret != LDB_SUCCESS) {
-               return ret;
-       }
-
-       ret = ldb_set_timeout_from_prev_req(module->ldb, req, new_req);
-       
+                                  subtree_rename_search_callback,
+                                  req);
        if (ret != LDB_SUCCESS) {
                return ret;
        }
 
-       ac->down_req = talloc_realloc(ac, ac->down_req, 
-                                       struct ldb_request *, ac->num_requests + 1);
-       if (!ac->down_req) {
-               ldb_oom(ac->module->ldb);
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-       ac->down_req[ac->num_requests] = new_req;
-       if (req == NULL) {
-               ldb_oom(ac->module->ldb);
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-       ac->num_requests++;
-       return ldb_next_request(module, new_req);
-}
-
-
-static int subtree_rename_wait_none(struct ldb_handle *handle) {
-       struct subtree_rename_context *ac;
-       int i, ret = LDB_ERR_OPERATIONS_ERROR;
-       if (!handle || !handle->private_data) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       if (handle->state == LDB_ASYNC_DONE) {
-               return handle->status;
-       }
-
-       handle->state = LDB_ASYNC_PENDING;
-       handle->status = LDB_SUCCESS;
-
-       ac = talloc_get_type(handle->private_data, struct subtree_rename_context);
-
-       for (i=0; i < ac->num_requests; i++) {
-               ret = ldb_wait(ac->down_req[i]->handle, LDB_WAIT_NONE);
-               
-               if (ret != LDB_SUCCESS) {
-                       handle->status = ret;
-                       goto done;
-               }
-               if (ac->down_req[i]->handle->status != LDB_SUCCESS) {
-                       handle->status = ac->down_req[i]->handle->status;
-                       goto done;
-               }
-               
-               if (ac->down_req[i]->handle->state != LDB_ASYNC_DONE) {
-                       return LDB_SUCCESS;
-               }
-       }
-
-done:
-       handle->state = LDB_ASYNC_DONE;
-       return ret;
-
-}
-
-static int subtree_rename_wait_all(struct ldb_handle *handle) {
-
-       int ret;
-
-       while (handle->state != LDB_ASYNC_DONE) {
-               ret = subtree_rename_wait_none(handle);
-               if (ret != LDB_SUCCESS) {
-                       return ret;
-               }
-       }
-
-       return handle->status;
-}
-
-static int subtree_rename_wait(struct ldb_handle *handle, enum ldb_wait_type type)
-{
-       if (type == LDB_WAIT_ALL) {
-               return subtree_rename_wait_all(handle);
-       } else {
-               return subtree_rename_wait_none(handle);
-       }
+       return ldb_next_request(module, search_req);
 }
 
 const struct ldb_module_ops ldb_subtree_rename_module_ops = {
        .name              = "subtree_rename",
        .rename            = subtree_rename,
-       .wait              = subtree_rename_wait,
 };
index 2ca5b80c67e9f015a7c97f0a47b2151ed22cc113..1fc531902d9618aeb678e88186e2844205283d1d 100644 (file)
@@ -26,7 +26,10 @@ import os
 import ldb
 from ldb import SCOPE_DEFAULT, SCOPE_BASE, SCOPE_SUBTREE
 from samba import Ldb, substitute_var
-from samba.tests import LdbTestCase, TestCaseInTempDir
+from samba.tests import LdbTestCase, TestCaseInTempDir, cmdline_loadparm
+import samba.dcerpc.security
+import samba.security
+import samba.ndr
 
 datadir = os.path.join(os.path.dirname(__file__), 
                        "../../../../../testdata/samba3")
@@ -76,7 +79,7 @@ class MapBaseTestCase(TestCaseInTempDir):
                 self.url = "tdb://" + self.file
                 self.basedn = basedn
                 self.substvars = {"BASEDN": self.basedn}
-                self.db = Ldb()
+                self.db = Ldb(lp=cmdline_loadparm)
                 self._dn = dn
 
             def dn(self, rdn):
@@ -112,19 +115,31 @@ class MapBaseTestCase(TestCaseInTempDir):
         os.unlink(self.samba4.file)
         super(MapBaseTestCase, self).tearDown()
 
+    def assertSidEquals(self, text, ndr_sid):
+        sid_obj1 = samba.ndr.ndr_unpack(samba.dcerpc.security.dom_sid, 
+                                        str(ndr_sid[0]))
+        sid_obj2 = samba.security.Sid(text)
+        # For now, this is the only way we can compare these since the 
+        # classes are in different places. Should reconcile that at some point.
+        self.assertEquals(sid_obj1.sid_rev_num, sid_obj2.sid_rev_num)
+        self.assertEquals(sid_obj1.num_auths, sid_obj2.num_auths)
+        # FIXME: self.assertEquals(sid_obj1.id_auth, sid_obj2.id_auth)
+        # FIXME: self.assertEquals(sid_obj1.sub_auths[:sid_obj1.num_auths], 
+        #                  sid_obj2.sub_auths[:sid_obj2.num_auths])
+
 
 class Samba3SamTestCase(MapBaseTestCase):
 
     def setUp(self):
         super(Samba3SamTestCase, self).setUp()
-        ldb = Ldb(self.ldburl)
+        ldb = Ldb(self.ldburl, lp=cmdline_loadparm)
         self.samba3.setup_data("samba3.ldif")
         self.templates.setup_data("provision_samba3sam_templates.ldif")
         ldif = read_datafile("provision_samba3sam.ldif")
         ldb.add_ldif(self.samba4.subst(ldif))
         self.setup_modules(ldb, self.samba3, self.samba4)
         del ldb
-        self.ldb = Ldb(self.ldburl)
+        self.ldb = Ldb(self.ldburl, lp=cmdline_loadparm)
 
     def test_search_non_mapped(self):
         """Looking up by non-mapped attribute"""
@@ -150,10 +165,8 @@ class Samba3SamTestCase(MapBaseTestCase):
         self.assertEquals(str(msg[0].dn), 
                           "cn=Replicator,ou=Groups,dc=vernstok,dc=nl")
         self.assertTrue("objectSid" in msg[0]) 
-        # FIXME: NDR unpack msg[0]["objectSid"] before comparing:
-        # self.assertEquals(msg[0]["objectSid"], 
-        #                   "S-1-5-21-4231626423-2410014848-2360679739-552")
-        # Check mapping of objectClass
+        self.assertSidEquals("S-1-5-21-4231626423-2410014848-2360679739-552",
+                             msg[0]["objectSid"])
         oc = set(msg[0]["objectClass"])
         self.assertEquals(oc, set(["group"]))
 
@@ -287,13 +300,13 @@ class MapTestCase(MapBaseTestCase):
 
     def setUp(self):
         super(MapTestCase, self).setUp()
-        ldb = Ldb(self.ldburl)
+        ldb = Ldb(self.ldburl, lp=cmdline_loadparm)
         self.templates.setup_data("provision_samba3sam_templates.ldif")
         ldif = read_datafile("provision_samba3sam.ldif")
         ldb.add_ldif(self.samba4.subst(ldif))
         self.setup_modules(ldb, self.samba3, self.samba4)
         del ldb
-        self.ldb = Ldb(self.ldburl)
+        self.ldb = Ldb(self.ldburl, lp=cmdline_loadparm)
 
     def test_map_search(self):
         """Running search tests on mapped data."""
@@ -459,17 +472,14 @@ primaryGroupID: 1-5-21-4231626423-2410014848-2360679739-512
         self.assertEquals(str(res[0].dn), self.samba4.dn("cn=X"))
         self.assertEquals(res[0]["dnsHostName"], "x")
         self.assertEquals(res[0]["lastLogon"], "x")
-        # FIXME:Properly compare sid,requires converting between NDR encoding 
-        # and string
-        #self.assertEquals(res[0]["objectSid"], 
-        #                  "S-1-5-21-4231626423-2410014848-2360679739-552")
+        self.assertSidEquals("S-1-5-21-4231626423-2410014848-2360679739-552", 
+                             res[0]["objectSid"])
         self.assertTrue("objectSid" in res[0])
         self.assertEquals(str(res[1].dn), self.samba4.dn("cn=A"))
         self.assertTrue(not "dnsHostName" in res[1])
         self.assertEquals(res[1]["lastLogon"], "x")
-        # FIXME: Properly compare sid,see above
-        #self.assertEquals(res[1]["objectSid"], 
-        #                  "S-1-5-21-4231626423-2410014848-2360679739-552")
+        self.assertSidEquals("S-1-5-21-4231626423-2410014848-2360679739-552",
+                             res[1]["objectSid"])
         self.assertTrue("objectSid" in res[1])
 
         # Search by generated attribute 
index 68973124ebe21f96d077ac449783df179200d60f..2c6cb102d978b0a56872d7d4ff600ae419bdc8ac 100644 (file)
@@ -43,6 +43,39 @@ struct update_kt_private {
        struct dn_list *changed_dns;
 };
 
+struct update_kt_ctx {
+       struct ldb_module *module;
+       struct ldb_request *req;
+
+       struct ldb_dn *dn;
+       bool delete;
+
+       struct ldb_reply *op_reply;
+       bool found;
+};
+
+struct update_kt_ctx *update_kt_ctx_init(struct ldb_module *module,
+                                        struct ldb_request *req)
+{
+       struct update_kt_ctx *ac;
+
+       ac = talloc_zero(req, struct update_kt_ctx);
+       if (ac == NULL) {
+               ldb_oom(module->ldb);
+               return NULL;
+       }
+
+       ac->module = module;
+       ac->req = req;
+
+       return ac;
+}
+
+/* FIXME: too many semi-async searches here for my taste, direct and indirect as
+ * cli_credentials_set_secrets() performs a sync ldb search.
+ * Just hope we are lucky and nothing breaks (using the tdb backend masks a lot
+ * of async issues). -SSS
+ */
 static int add_modified(struct ldb_module *module, struct ldb_dn *dn, bool delete) {
        struct update_kt_private *data = talloc_get_type(module->private_data, struct update_kt_private);
        struct dn_list *item;
@@ -80,7 +113,7 @@ static int add_modified(struct ldb_module *module, struct ldb_dn *dn, bool delet
                ldb_oom(module->ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       
+
        item->creds = cli_credentials_init(item);
        if (!item->creds) {
                DEBUG(1, ("cli_credentials_init failed!"));
@@ -90,7 +123,7 @@ static int add_modified(struct ldb_module *module, struct ldb_dn *dn, bool delet
        }
 
        cli_credentials_set_conf(item->creds, ldb_get_opaque(module->ldb, "loadparm"));
-       status = cli_credentials_set_secrets(item->creds, ldb_get_opaque(module->ldb, "EventContext"), ldb_get_opaque(module->ldb, "loadparm"), module->ldb, NULL, filter);
+       status = cli_credentials_set_secrets(item->creds, ldb_get_event_context(module->ldb), ldb_get_opaque(module->ldb, "loadparm"), module->ldb, NULL, filter);
        talloc_free(filter);
        if (NT_STATUS_IS_OK(status)) {
                if (delete) {
@@ -105,60 +138,237 @@ static int add_modified(struct ldb_module *module, struct ldb_dn *dn, bool delet
        return LDB_SUCCESS;
 }
 
+static int ukt_search_modified(struct update_kt_ctx *ac);
+
+static int update_kt_op_callback(struct ldb_request *req,
+                                struct ldb_reply *ares)
+{
+       struct update_kt_ctx *ac;
+       int ret;
+
+       ac = talloc_get_type(req->context, struct update_kt_ctx);
+
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
+
+       if (ares->type != LDB_REPLY_DONE) {
+               ldb_set_errstring(ac->module->ldb, "Invalid request type!\n");
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+
+       if (ac->delete) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, LDB_SUCCESS);
+       }
+
+       ac->op_reply = talloc_steal(ac, ares);
+
+       ret = ukt_search_modified(ac);
+       if (ret != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, NULL, NULL, ret);
+       }
+
+       return LDB_SUCCESS;
+}
+
+static int ukt_del_op(struct update_kt_ctx *ac)
+{
+       struct ldb_request *down_req;
+       int ret;
+
+       ret = ldb_build_del_req(&down_req, ac->module->ldb, ac,
+                               ac->dn,
+                               ac->req->controls,
+                               ac, update_kt_op_callback,
+                               ac->req);
+       if (ret != LDB_SUCCESS) {
+               return ret;
+       }
+       return ldb_next_request(ac->module, down_req);
+}
+
+static int ukt_search_modified_callback(struct ldb_request *req,
+                                       struct ldb_reply *ares)
+{
+       struct update_kt_ctx *ac;
+       int ret;
+
+       ac = talloc_get_type(req->context, struct update_kt_ctx);
+
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
+
+       switch (ares->type) {
+       case LDB_REPLY_ENTRY:
+
+               ac->found = true;
+               break;
+
+       case LDB_REPLY_REFERRAL:
+               /* ignore */
+               break;
+
+       case LDB_REPLY_DONE:
+
+               if (ac->found) {
+                       /* do the dirty sync job here :/ */
+                       ret = add_modified(ac->module, ac->dn, ac->delete);
+               }
+
+               if (ac->delete) {
+                       ret = ukt_del_op(ac);
+                       if (ret != LDB_SUCCESS) {
+                               return ldb_module_done(ac->req,
+                                                       NULL, NULL, ret);
+                       }
+                       break;
+               }
+
+               return ldb_module_done(ac->req, ac->op_reply->controls,
+                                       ac->op_reply->response, LDB_SUCCESS);
+       }
+
+       talloc_free(ares);
+       return LDB_SUCCESS;
+}
+
+static int ukt_search_modified(struct update_kt_ctx *ac)
+{
+       static const char * const attrs[] = { "distinguishedName", NULL };
+       struct ldb_request *search_req;
+       int ret;
+
+       ret = ldb_build_search_req(&search_req, ac->module->ldb, ac,
+                                  ac->dn, LDB_SCOPE_BASE,
+                                  "(&(objectClass=kerberosSecret)"
+                                    "(privateKeytab=*))", attrs,
+                                  NULL,
+                                  ac, ukt_search_modified_callback,
+                                  ac->req);
+       if (ret != LDB_SUCCESS) {
+               return ret;
+       }
+       return ldb_next_request(ac->module, search_req);
+}
+
+
 /* add */
 static int update_kt_add(struct ldb_module *module, struct ldb_request *req)
 {
+       struct update_kt_ctx *ac;
+       struct ldb_request *down_req;
        int ret;
-       ret = ldb_next_request(module, req);
+
+       ac = update_kt_ctx_init(module, req);
+       if (ac == NULL) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       ac->dn = req->op.add.message->dn;
+
+       ret = ldb_build_add_req(&down_req, module->ldb, ac,
+                               req->op.add.message,
+                               req->controls,
+                               ac, update_kt_op_callback,
+                               req);
        if (ret != LDB_SUCCESS) {
                return ret;
        }
-       return add_modified(module, req->op.add.message->dn, false);
+
+       return ldb_next_request(module, down_req);
 }
 
 /* modify */
 static int update_kt_modify(struct ldb_module *module, struct ldb_request *req)
 {
+       struct update_kt_ctx *ac;
+       struct ldb_request *down_req;
        int ret;
-       ret = ldb_next_request(module, req);
+
+       ac = update_kt_ctx_init(module, req);
+       if (ac == NULL) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       ac->dn = req->op.mod.message->dn;
+
+       ret = ldb_build_mod_req(&down_req, module->ldb, ac,
+                               req->op.mod.message,
+                               req->controls,
+                               ac, update_kt_op_callback,
+                               req);
        if (ret != LDB_SUCCESS) {
                return ret;
        }
-       return add_modified(module, req->op.mod.message->dn, false);
+
+       return ldb_next_request(module, down_req);
 }
 
 /* delete */
 static int update_kt_delete(struct ldb_module *module, struct ldb_request *req)
 {
-       int ret;
-       /* Before we delete it, record the details */
-       ret = add_modified(module, req->op.del.dn, true);
-       if (ret != LDB_SUCCESS) {
-               return ret;
+       struct update_kt_ctx *ac;
+
+       ac = update_kt_ctx_init(module, req);
+       if (ac == NULL) {
+               return LDB_ERR_OPERATIONS_ERROR;
        }
-       return ldb_next_request(module, req);
+
+       ac->dn = req->op.del.dn;
+       ac->delete = true;
+
+       return ukt_search_modified(ac);
 }
 
 /* rename */
 static int update_kt_rename(struct ldb_module *module, struct ldb_request *req)
 {
+       struct update_kt_ctx *ac;
+       struct ldb_request *down_req;
        int ret;
-       ret = ldb_next_request(module, req);
+
+       ac = update_kt_ctx_init(module, req);
+       if (ac == NULL) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       ac->dn = req->op.rename.newdn;
+
+       ret = ldb_build_rename_req(&down_req, module->ldb, ac,
+                               req->op.rename.olddn,
+                               req->op.rename.newdn,
+                               req->controls,
+                               ac, update_kt_op_callback,
+                               req);
        if (ret != LDB_SUCCESS) {
                return ret;
        }
-       return add_modified(module, req->op.rename.newdn, false);
+
+       return ldb_next_request(module, down_req);
 }
 
 /* end a transaction */
 static int update_kt_end_trans(struct ldb_module *module)
 {
        struct update_kt_private *data = talloc_get_type(module->private_data, struct update_kt_private);
-       
        struct dn_list *p;
+
        for (p=data->changed_dns; p; p = p->next) {
                int kret;
-               kret = cli_credentials_update_keytab(p->creds, ldb_get_opaque(module->ldb, "EventContext"), ldb_get_opaque(module->ldb, "loadparm"));
+               kret = cli_credentials_update_keytab(p->creds, ldb_get_event_context(module->ldb), ldb_get_opaque(module->ldb, "loadparm"));
                if (kret != 0) {
                        talloc_free(data->changed_dns);
                        data->changed_dns = NULL;
@@ -169,6 +379,7 @@ static int update_kt_end_trans(struct ldb_module *module)
 
        talloc_free(data->changed_dns);
        data->changed_dns = NULL;
+
        return ldb_next_end_trans(module);
 }
 
@@ -176,7 +387,7 @@ static int update_kt_end_trans(struct ldb_module *module)
 static int update_kt_del_trans(struct ldb_module *module)
 {
        struct update_kt_private *data = talloc_get_type(module->private_data, struct update_kt_private);
-       
+
        talloc_free(data->changed_dns);
        data->changed_dns = NULL;
 
index f24a75fd8f0c0f939669c7a17ace6491be85bd74..93068d66ef1dd4b47382c3445cd3bc54cef74c51 100644 (file)
@@ -56,6 +56,9 @@ struct dsdb_control_current_partition {
        struct ldb_module *module;
 };
 
+#define DSDB_CONTROL_REPLICATED_UPDATE_OID "1.3.6.1.4.1.7165.4.3.3"
+/* DSDB_CONTROL_REPLICATED_UPDATE_OID has NULL data */
+
 #define DSDB_EXTENDED_REPLICATED_OBJECTS_OID "1.3.6.1.4.1.7165.4.4.1"
 struct dsdb_extended_replicated_object {
        struct ldb_message *msg;
index 6884c5284e4d74614279fb64c84fd0bad5685f05..c3c37b46533320b56bb2e4ebcb8f6f68c6843aa8 100644 (file)
@@ -33,7 +33,6 @@ char *schema_attribute_description(TALLOC_CTX *mem_ctx,
                                          const char *seperator,
                                          const char *oid, 
                                          const char *name,
-                                         const char *description,
                                          const char *equality, 
                                          const char *substring, 
                                          const char *syntax,
@@ -46,15 +45,6 @@ char *schema_attribute_description(TALLOC_CTX *mem_ctx,
                                              "NAME '%s'%s", name, seperator);
        IF_NULL_FAIL_RET(schema_entry);
        
-       if (description) {
-#if 0          
-               /* Need a way to escape ' characters from the description */
-               schema_entry = talloc_asprintf_append(schema_entry, 
-                                                     "DESC '%s'%s", description, seperator);
-               IF_NULL_FAIL_RET(schema_entry);
-#endif
-       }
-
        if (equality) {
                schema_entry = talloc_asprintf_append(schema_entry, 
                                                      "EQUALITY %s%s", equality, seperator);
@@ -104,7 +94,7 @@ char *schema_attribute_to_description(TALLOC_CTX *mem_ctx, const struct dsdb_att
                                               " ",
                                               attribute->attributeID_oid,
                                               attribute->lDAPDisplayName,
-                                              NULL, NULL, NULL, talloc_asprintf(tmp_ctx, "'%s'", syntax),
+                                              NULL, NULL, talloc_asprintf(tmp_ctx, "'%s'", syntax),
                                               attribute->isSingleValued,
                                               attribute->systemOnly);
        talloc_free(tmp_ctx);
@@ -149,7 +139,6 @@ char *schema_class_description(TALLOC_CTX *mem_ctx,
                               const char *oid, 
                               const char *name,
                               const char **auxillary_classes,
-                              const char *description,
                               const char *subClassOf,
                               int objectClassCategory,
                               char **must,
@@ -164,12 +153,6 @@ char *schema_class_description(TALLOC_CTX *mem_ctx,
                                              "NAME '%s'%s", name, seperator);
        IF_NULL_FAIL_RET(schema_entry);
        
-       if (description) {
-               schema_entry = talloc_asprintf_append(schema_entry, 
-                                                     "DESC '%s'%s", description, seperator);
-               IF_NULL_FAIL_RET(schema_entry);
-       }
-
        if (auxillary_classes) {
                schema_entry = talloc_asprintf_append(schema_entry, 
                                                      "AUX ( ");
@@ -262,7 +245,6 @@ char *schema_class_to_description(TALLOC_CTX *mem_ctx, const struct dsdb_class *
                                           " ",
                                           class->governsID_oid,
                                           class->lDAPDisplayName,
-                                          NULL,
                                           NULL, 
                                           class->subClassOf,
                                           class->objectClassCategory,
@@ -308,8 +290,11 @@ char *schema_class_to_dITContentRule(TALLOC_CTX *mem_ctx, const struct dsdb_clas
                                           class->governsID_oid,
                                           class->lDAPDisplayName,
                                           (const char **)aux_class_list,
-                                          NULL, 
-                                          class->subClassOf,
+                                          NULL, /* Must not specify a
+                                                 * SUP (subclass) in
+                                                 * ditContentRules
+                                                 * per MS-ADTS
+                                                 * 3.1.1.3.1.1.1 */
                                           -1, must_attr_list, may_attr_list);
        talloc_free(tmp_ctx);
        return schema_description;
index 699c30e764837cdc235d98806348ad284ed469bd..f79cdb8e750792b92c1880f9363856949a97c828 100644 (file)
@@ -6,19 +6,19 @@ DYNCONFIG_OBJ_FILES = $(dynconfigsrcdir)/dynconfig.o
 # These can be overridden by command line switches (see samba(8))
 # or in smb.conf (see smb.conf(5))
 CONFIG4FILE = $(sysconfdir)/smb.conf
-PKGCONFIGDIR = $(libdir)/pkgconfig
+pkgconfigdir = $(libdir)/pkgconfig
 LMHOSTSFILE4 = $(sysconfdir)/lmhosts
 
 $(dynconfigsrcdir)/dynconfig.o: CFLAGS+=-DCONFIGFILE=\"$(CONFIG4FILE)\" -DBINDIR=\"$(bindir)\" \
         -DLMHOSTSFILE=\"$(LMHOSTSFILE4)\" \
         -DLOCKDIR=\"$(lockdir)\" -DPIDDIR=\"$(piddir)\" -DDATADIR=\"$(datadir)\" \
         -DLOGFILEBASE=\"$(logfilebase)\" \
-        -DCONFIGDIR=\"$(sysconfdir)\" -DNCALRPCDIR=\"$(NCALRPCDIR)\" \
-        -DSWATDIR=\"$(SWATDIR)\" \
+        -DCONFIGDIR=\"$(sysconfdir)\" -DNCALRPCDIR=\"$(ncalrpcdir)\" \
+        -DSWATDIR=\"$(swatdir)\" \
         -DPRIVATE_DIR=\"$(privatedir)\" \
-        -DMODULESDIR=\"$(modulesdir)\" -DJSDIR=\"$(JSDIR)\" \
-        -DTORTUREDIR=\"$(TORTUREDIR)\" \
-        -DSETUPDIR=\"$(SETUPDIR)\" \
+        -DMODULESDIR=\"$(modulesdir)\" \
+        -DTORTUREDIR=\"$(torturedir)\" \
+        -DSETUPDIR=\"$(setupdir)\" \
         -DWINBINDD_PRIVILEGED_SOCKET_DIR=\"$(winbindd_privileged_socket_dir)\" \
         -DWINBINDD_SOCKET_DIR=\"$(winbindd_socket_dir)\" \
         -DNTP_SIGND_SOCKET_DIR=\"$(ntp_signd_socket_dir)\"
index 507570318d97773fbe756e2f613e9589e8e4f92e..e0cabef317b828b2b64a9f7cb534c30a1e631da3 100644 (file)
@@ -79,9 +79,6 @@ _PUBLIC_ const char *dyn_SWATDIR = SWATDIR;
 /** SETUP files (source files used by the provision) */
 _PUBLIC_ const char *dyn_SETUPDIR = SETUPDIR;
 
-/** EJS Javascript library includes */
-_PUBLIC_ const char *dyn_JSDIR = JSDIR;
-
 /** Where to find the winbindd socket */
 _PUBLIC_ const char *dyn_WINBINDD_SOCKET_DIR = WINBINDD_SOCKET_DIR;
 
index 19dff5e01df3347d5070eda3bbe221f1d463bed3..d557da2a5b8a6d28160b346594b4f6f4c1c7ca61 100644 (file)
@@ -1393,6 +1393,8 @@ tgs_build_reply(krb5_context context,
     char opt_str[128];
     int signedpath = 0;
 
+    Key *tkey;
+
     memset(&sessionkey, 0, sizeof(sessionkey));
     memset(&adtkt, 0, sizeof(adtkt));
     krb5_data_zero(&rspac);
@@ -1630,26 +1632,22 @@ server_lookup:
     }
 
     /* check PAC if not cross realm and if there is one */
-    if (!cross_realm) {
-       Key *tkey;
-
-       ret = hdb_enctype2key(context, &krbtgt->entry,
-                             krbtgt_etype, &tkey);
-       if(ret) {
-           kdc_log(context, config, 0,
+    ret = hdb_enctype2key(context, &krbtgt->entry,
+                         krbtgt_etype, &tkey);
+    if(ret) {
+       kdc_log(context, config, 0,
                    "Failed to find key for krbtgt PAC check");
-           goto out;
-       }
+       goto out;
+    }
 
-       ret = check_PAC(context, config, cp,
-                       client, server, ekey, &tkey->key,
-                       tgt, &rspac, &signedpath);
-       if (ret) {
-           kdc_log(context, config, 0,
-                   "Verify PAC failed for %s (%s) from %s with %s",
-                   spn, cpn, from, krb5_get_err_text(context, ret));
-           goto out;
-       }
+    ret = check_PAC(context, config, cp,
+                   client, server, ekey, &tkey->key,
+                   tgt, &rspac, &signedpath);
+    if (ret) {
+       kdc_log(context, config, 0,
+               "Verify PAC failed for %s (%s) from %s with %s",
+               spn, cpn, from, krb5_get_err_text(context, ret));
+       goto out;
     }
 
     /* also check the krbtgt for signature */
index 3fddabb2d08dad3d3bd715b4ee1f5d871bcb87ca..19c170767dfab78e99ad80697985c892b4fab9ef 100644 (file)
  * SUCH DAMAGE. 
  */
 
+#include "krb5.h"
+#include "krb5_locl.h"
 #include "hdb_locl.h"
-
 RCSID("$Id$");
 
 #ifdef HAVE_DLFCN_H
 #include <dlfcn.h>
 #endif
 
-struct hdb_method {
-    const char *prefix;
-    krb5_error_code (*create)(krb5_context, HDB **, const char *filename);
-};
-
 static struct hdb_method methods[] = {
 #if HAVE_DB1 || HAVE_DB3
-    {"db:",    hdb_db_create},
+    {HDB_INTERFACE_VERSION, "db:",     hdb_db_create},
 #endif
 #if HAVE_NDBM
-    {"ndbm:",  hdb_ndbm_create},
+    {HDB_INTERFACE_VERSION, "ndbm:",   hdb_ndbm_create},
 #endif
 #if defined(OPENLDAP) && !defined(OPENLDAP_MODULE)
-    {"ldap:",  hdb_ldap_create},
-    {"ldapi:", hdb_ldapi_create},
-#endif
-#ifdef HAVE_LDB /* Used for integrated samba build */
-    {"ldb:",   hdb_ldb_create},
+    {HDB_INTERFACE_VERSION, "ldap:",   hdb_ldap_create},
+    {HDB_INTERFACE_VERSION, "ldapi:",  hdb_ldapi_create},
 #endif
-    {NULL,     NULL}
+    {0, NULL,  NULL}
 };
 
 #if HAVE_DB1 || HAVE_DB3
@@ -398,11 +391,32 @@ hdb_create(krb5_context context, HDB **db, const char *filename)
 {
     const struct hdb_method *h;
     const char *residual;
+    krb5_error_code ret;
+    struct krb5_plugin *list = NULL, *e;
 
     if(filename == NULL)
        filename = HDB_DEFAULT_DB;
     krb5_add_et_list(context, initialize_hdb_error_table_r);
     h = find_method (filename, &residual);
+
+    if (h == NULL) {
+           ret = _krb5_plugin_find(context, PLUGIN_TYPE_DATA, "hdb", &list);
+           if(ret == 0 && list != NULL) {
+                   for (e = list; e != NULL; e = _krb5_plugin_get_next(e)) {
+                           h = _krb5_plugin_get_symbol(e);
+                           if (strncmp (filename, h->prefix, strlen(h->prefix)) == 0
+                               && h->interface_version == HDB_INTERFACE_VERSION) {
+                                   residual = filename + strlen(h->prefix);
+                                   break;
+                           }
+                   }
+                   if (e == NULL) {
+                           h = NULL;
+                           _krb5_plugin_free(list);
+                   }
+           }
+    }
+
 #ifdef HAVE_DLOPEN
     if (h == NULL)
        h = find_dynamic_method (context, filename, &residual);
index bc1b744015cbb5776b6a1a5a9203c59d7136404b..5c2097ea59c436e4b53a1ad1f688bd85533e565e 100644 (file)
@@ -139,6 +139,12 @@ typedef krb5_error_code (*hdb_foreach_func_t)(krb5_context, HDB*,
                                              hdb_entry_ex*, void*);
 extern krb5_kt_ops hdb_kt_ops;
 
+struct hdb_method {
+    int        interface_version;
+    const char *prefix;
+    krb5_error_code (*create)(krb5_context, HDB **, const char *filename);
+};
+
 #include <hdb-protos.h>
 
 #endif /* __HDB_H__ */
index b3e5bfdb92f102b1fd4a5348eb06adb477de7956..dfd2879bd600b61dc79d4e0aa979b72d562d0046 100644 (file)
@@ -6,7 +6,7 @@
 INIT_FUNCTION = server_service_kdc_init
 SUBSYSTEM = samba
 PRIVATE_DEPENDENCIES = \
-               HEIMDAL_KDC HDB_LDB
+               HEIMDAL_KDC HDB_SAMBA4
 # End SUBSYSTEM KDC
 #######################
 
@@ -14,7 +14,7 @@ KDC_OBJ_FILES = $(addprefix $(kdcsrcdir)/, kdc.o kpasswdd.o)
 
 #######################
 # Start SUBSYSTEM KDC
-[SUBSYSTEM::HDB_LDB]
+[SUBSYSTEM::HDB_SAMBA4]
 CFLAGS = -Iheimdal/kdc -Iheimdal/lib/hdb
 PRIVATE_DEPENDENCIES = \
                LIBLDB auth_sam auth_sam_reply CREDENTIALS \
@@ -22,5 +22,5 @@ PRIVATE_DEPENDENCIES = \
 # End SUBSYSTEM KDC
 #######################
 
-HDB_LDB_OBJ_FILES = $(addprefix $(kdcsrcdir)/, hdb-ldb.o pac-glue.o)
-$(eval $(call proto_header_template,$(kdcsrcdir)/pac_glue.h,$(HDB_LDB_OBJ_FILES:.o=.c)))
+HDB_SAMBA4_OBJ_FILES = $(addprefix $(kdcsrcdir)/, hdb-samba4.o pac-glue.o)
+$(eval $(call proto_header_template,$(kdcsrcdir)/pac_glue.h,$(HDB_SAMBA4_OBJ_FILES:.o=.c)))
similarity index 95%
rename from source4/kdc/hdb-ldb.c
rename to source4/kdc/hdb-samba4.c
index c5466f1acd3e2a9aa49cae26b60ca9a41135a3af..51f464cd096c75838a53b2926373a2d748fa9bda 100644 (file)
@@ -53,8 +53,8 @@
 #include "../lib/crypto/md4.h"
 
 enum hdb_ldb_ent_type 
-{ HDB_LDB_ENT_TYPE_CLIENT, HDB_LDB_ENT_TYPE_SERVER, 
-  HDB_LDB_ENT_TYPE_KRBTGT, HDB_LDB_ENT_TYPE_TRUST, HDB_LDB_ENT_TYPE_ANY };
+{ HDB_SAMBA4_ENT_TYPE_CLIENT, HDB_SAMBA4_ENT_TYPE_SERVER, 
+  HDB_SAMBA4_ENT_TYPE_KRBTGT, HDB_SAMBA4_ENT_TYPE_TRUST, HDB_SAMBA4_ENT_TYPE_ANY };
 
 enum trust_direction {
        UNKNOWN = 0,
@@ -115,26 +115,26 @@ static HDBFlags uf2HDBFlags(krb5_context context, int userAccountControl, enum h
 
        /* Account types - clear the invalid bit if it turns out to be valid */
        if (userAccountControl & UF_NORMAL_ACCOUNT) {
-               if (ent_type == HDB_LDB_ENT_TYPE_CLIENT || ent_type == HDB_LDB_ENT_TYPE_ANY) {
+               if (ent_type == HDB_SAMBA4_ENT_TYPE_CLIENT || ent_type == HDB_SAMBA4_ENT_TYPE_ANY) {
                        flags.client = 1;
                }
                flags.invalid = 0;
        }
        
        if (userAccountControl & UF_INTERDOMAIN_TRUST_ACCOUNT) {
-               if (ent_type == HDB_LDB_ENT_TYPE_CLIENT || ent_type == HDB_LDB_ENT_TYPE_ANY) {
+               if (ent_type == HDB_SAMBA4_ENT_TYPE_CLIENT || ent_type == HDB_SAMBA4_ENT_TYPE_ANY) {
                        flags.client = 1;
                }
                flags.invalid = 0;
        }
        if (userAccountControl & UF_WORKSTATION_TRUST_ACCOUNT) {
-               if (ent_type == HDB_LDB_ENT_TYPE_CLIENT || ent_type == HDB_LDB_ENT_TYPE_ANY) {
+               if (ent_type == HDB_SAMBA4_ENT_TYPE_CLIENT || ent_type == HDB_SAMBA4_ENT_TYPE_ANY) {
                        flags.client = 1;
                }
                flags.invalid = 0;
        }
        if (userAccountControl & UF_SERVER_TRUST_ACCOUNT) {
-               if (ent_type == HDB_LDB_ENT_TYPE_CLIENT || ent_type == HDB_LDB_ENT_TYPE_ANY) {
+               if (ent_type == HDB_SAMBA4_ENT_TYPE_CLIENT || ent_type == HDB_SAMBA4_ENT_TYPE_ANY) {
                        flags.client = 1;
                }
                flags.invalid = 0;
@@ -186,7 +186,7 @@ static HDBFlags uf2HDBFlags(krb5_context context, int userAccountControl, enum h
        return flags;
 }
 
-static int hdb_ldb_destrutor(struct hdb_ldb_private *private)
+static int hdb_ldb_destructor(struct hdb_ldb_private *private)
 {
     hdb_entry_ex *entry_ex = private->entry_ex;
     free_hdb_entry(&entry_ex->entry);
@@ -542,7 +542,7 @@ static krb5_error_code LDB_message2entry(krb5_context context, HDB *db,
        private->iconv_convenience = lp_iconv_convenience(lp_ctx);
        private->netbios_name = lp_netbios_name(lp_ctx);
 
-       talloc_set_destructor(private, hdb_ldb_destrutor);
+       talloc_set_destructor(private, hdb_ldb_destructor);
 
        entry_ex->ctx = private;
        entry_ex->free_entry = hdb_ldb_free_entry;
@@ -551,7 +551,7 @@ static krb5_error_code LDB_message2entry(krb5_context context, HDB *db,
 
        
        entry_ex->entry.principal = malloc(sizeof(*(entry_ex->entry.principal)));
-       if (ent_type == HDB_LDB_ENT_TYPE_ANY && principal == NULL) {
+       if (ent_type == HDB_SAMBA4_ENT_TYPE_ANY && principal == NULL) {
                const char *samAccountName = ldb_msg_find_attr_as_string(msg, "samAccountName", NULL);
                if (!samAccountName) {
                        krb5_set_error_string(context, "LDB_message2entry: no samAccountName present");
@@ -587,7 +587,7 @@ static krb5_error_code LDB_message2entry(krb5_context context, HDB *db,
 
        entry_ex->entry.flags = uf2HDBFlags(context, userAccountControl, ent_type);
 
-       if (ent_type == HDB_LDB_ENT_TYPE_KRBTGT) {
+       if (ent_type == HDB_SAMBA4_ENT_TYPE_KRBTGT) {
                entry_ex->entry.flags.invalid = 0;
                entry_ex->entry.flags.server = 1;
                entry_ex->entry.flags.forwardable = 1;
@@ -631,7 +631,7 @@ static krb5_error_code LDB_message2entry(krb5_context context, HDB *db,
                *entry_ex->entry.valid_end = nt_time_to_unix(acct_expiry);
        }
 
-       if (ent_type != HDB_LDB_ENT_TYPE_KRBTGT) {
+       if (ent_type != HDB_SAMBA4_ENT_TYPE_KRBTGT) {
                NTTIME must_change_time
                        = samdb_result_force_password_change((struct ldb_context *)db->hdb_db, mem_ctx, 
                                                             domain_dn, msg);
@@ -728,7 +728,7 @@ static krb5_error_code LDB_trust_message2entry(krb5_context context, HDB *db,
        private->iconv_convenience = lp_iconv_convenience(lp_ctx);
        private->netbios_name = lp_netbios_name(lp_ctx);
 
-       talloc_set_destructor(private, hdb_ldb_destrutor);
+       talloc_set_destructor(private, hdb_ldb_destructor);
 
        entry_ex->ctx = private;
        entry_ex->free_entry = hdb_ldb_free_entry;
@@ -757,13 +757,20 @@ static krb5_error_code LDB_trust_message2entry(krb5_context context, HDB *db,
                goto out;
        }
 
-       ndr_err = ndr_pull_struct_blob_all(password_val, mem_ctx, private->iconv_convenience, &password_blob,
+       ndr_err = ndr_pull_struct_blob(password_val, mem_ctx, private->iconv_convenience, &password_blob,
                                           (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
        if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
                ret = EINVAL;
                goto out;
        }
 
+       entry_ex->entry.kvno = -1;
+       for (i=0; i < password_blob.count; i++) {
+               if (password_blob.current->array[i].AuthType == TRUST_AUTH_TYPE_VERSION) {
+                       entry_ex->entry.kvno = password_blob.current->array[i].AuthInfo.version.version;
+               }
+       }
+
        for (i=0; i < password_blob.count; i++) {
                if (password_blob.current->array[i].AuthType == TRUST_AUTH_TYPE_CLEAR) {
                        password_utf16 = data_blob_const(password_blob.current->array[i].AuthInfo.clear.password,
@@ -806,6 +813,8 @@ static krb5_error_code LDB_trust_message2entry(krb5_context context, HDB *db,
                entry_ex->entry.keys.len++;
        }
                
+       entry_ex->entry.principal = malloc(sizeof(*(entry_ex->entry.principal)));
+
        ret = copy_Principal(principal, entry_ex->entry.principal);
        if (ret) {
                krb5_clear_error_string(context);
@@ -909,16 +918,16 @@ static krb5_error_code LDB_lookup_principal(krb5_context context, struct ldb_con
        }
 
        switch (ent_type) {
-       case HDB_LDB_ENT_TYPE_CLIENT:
-       case HDB_LDB_ENT_TYPE_TRUST:
-       case HDB_LDB_ENT_TYPE_ANY:
+       case HDB_SAMBA4_ENT_TYPE_CLIENT:
+       case HDB_SAMBA4_ENT_TYPE_TRUST:
+       case HDB_SAMBA4_ENT_TYPE_ANY:
                /* Can't happen */
                return EINVAL;
-       case HDB_LDB_ENT_TYPE_KRBTGT:
+       case HDB_SAMBA4_ENT_TYPE_KRBTGT:
                filter = talloc_asprintf(mem_ctx, "(&(objectClass=user)(samAccountName=%s))", 
                                         KRB5_TGS_NAME);
                break;
-       case HDB_LDB_ENT_TYPE_SERVER:
+       case HDB_SAMBA4_ENT_TYPE_SERVER:
                filter = talloc_asprintf(mem_ctx, "(&(objectClass=user)(samAccountName=%s))", 
                                         short_princ_talloc);
                break;
@@ -1075,7 +1084,7 @@ static krb5_error_code LDB_fetch_client(krb5_context context, HDB *db,
        }
        
        ret = LDB_message2entry(context, db, mem_ctx, 
-                               principal, HDB_LDB_ENT_TYPE_CLIENT,
+                               principal, HDB_SAMBA4_ENT_TYPE_CLIENT,
                                msg[0], realm_ref_msg[0], entry_ex);
        return ret;
 }
@@ -1136,7 +1145,7 @@ static krb5_error_code LDB_fetch_krbtgt(krb5_context context, HDB *db,
                
                ret = LDB_lookup_principal(context, (struct ldb_context *)db->hdb_db, 
                                           mem_ctx, 
-                                          principal, HDB_LDB_ENT_TYPE_KRBTGT, realm_dn, &msg);
+                                          principal, HDB_SAMBA4_ENT_TYPE_KRBTGT, realm_dn, &msg);
                
                if (ret != 0) {
                        krb5_warnx(context, "LDB_fetch: could not find principal in DB");
@@ -1145,10 +1154,10 @@ static krb5_error_code LDB_fetch_krbtgt(krb5_context context, HDB *db,
                }
                
                ret = LDB_message2entry(context, db, mem_ctx, 
-                                       principal, HDB_LDB_ENT_TYPE_KRBTGT, 
+                                       principal, HDB_SAMBA4_ENT_TYPE_KRBTGT, 
                                        msg[0], realm_ref_msg_1[0], entry_ex);
                if (ret != 0) {
-                       krb5_warnx(context, "LDB_fetch: message2entry failed"); 
+                       krb5_warnx(context, "LDB_fetch: self krbtgt message2entry failed");     
                }
                return ret;
 
@@ -1186,7 +1195,7 @@ static krb5_error_code LDB_fetch_krbtgt(krb5_context context, HDB *db,
                                              principal, direction, 
                                              msg[0], entry_ex);
                if (ret != 0) {
-                       krb5_warnx(context, "LDB_fetch: message2entry failed"); 
+                       krb5_warnx(context, "LDB_fetch: trust_message2entry failed");   
                }
                return ret;
 
@@ -1265,7 +1274,7 @@ static krb5_error_code LDB_fetch_server(krb5_context context, HDB *db,
                
                ret = LDB_lookup_principal(context, (struct ldb_context *)db->hdb_db, 
                                           mem_ctx, 
-                                          principal, HDB_LDB_ENT_TYPE_SERVER, realm_dn, &msg);
+                                          principal, HDB_SAMBA4_ENT_TYPE_SERVER, realm_dn, &msg);
                
                if (ret != 0) {
                        return ret;
@@ -1273,7 +1282,7 @@ static krb5_error_code LDB_fetch_server(krb5_context context, HDB *db,
        }
 
        ret = LDB_message2entry(context, db, mem_ctx, 
-                               principal, HDB_LDB_ENT_TYPE_SERVER,
+                               principal, HDB_SAMBA4_ENT_TYPE_SERVER,
                                msg[0], realm_ref_msg[0], entry_ex);
        if (ret != 0) {
                krb5_warnx(context, "LDB_fetch: message2entry failed"); 
@@ -1358,7 +1367,7 @@ static krb5_error_code LDB_seq(krb5_context context, HDB *db, unsigned flags, hd
 
        if (priv->index < priv->count) {
                ret = LDB_message2entry(context, db, mem_ctx, 
-                                       NULL, HDB_LDB_ENT_TYPE_ANY, 
+                                       NULL, HDB_SAMBA4_ENT_TYPE_ANY, 
                                        priv->msgs[priv->index++], 
                                        priv->realm_ref_msgs[0], entry);
        } else {
@@ -1476,7 +1485,7 @@ static krb5_error_code LDB_destroy(krb5_context context, HDB *db)
  * (hdb_ldb_create) from the kpasswdd -> krb5 -> keytab_hdb -> hdb
  * code */
 
-NTSTATUS kdc_hdb_ldb_create(TALLOC_CTX *mem_ctx, 
+NTSTATUS kdc_hdb_samba4_create(TALLOC_CTX *mem_ctx, 
                            struct event_context *ev_ctx, 
                            struct loadparm_context *lp_ctx,
                            krb5_context context, struct HDB **db, const char *arg)
@@ -1536,12 +1545,12 @@ NTSTATUS kdc_hdb_ldb_create(TALLOC_CTX *mem_ctx,
        return NT_STATUS_OK;
 }
 
-krb5_error_code hdb_ldb_create(krb5_context context, struct HDB **db, const char *arg)
+krb5_error_code hdb_samba4_create(krb5_context context, struct HDB **db, const char *arg)
 {
        NTSTATUS nt_status;
        /* The global kdc_mem_ctx and kdc_lp_ctx, Disgusting, ugly hack, but it means one less private hook */
-       nt_status = kdc_hdb_ldb_create(kdc_mem_ctx, event_context_find(kdc_mem_ctx), kdc_lp_ctx, 
-                                      context, db, arg);
+       nt_status = kdc_hdb_samba4_create(kdc_mem_ctx, event_context_find(kdc_mem_ctx), kdc_lp_ctx, 
+                                         context, db, arg);
 
        if (NT_STATUS_IS_OK(nt_status)) {
                return 0;
index 030eb23c10d8d8f33775a679fc8356e7c001d2c1..83c6f1c2ee15dc93a408c52bcfb2a7abb5ddb216 100644 (file)
@@ -667,6 +667,11 @@ static void kdc_task_init(struct task_server *task)
        NTSTATUS status;
        krb5_error_code ret;
        struct interface *ifaces;
+       struct hdb_method hdb_samba4 = {
+               .interface_version = HDB_INTERFACE_VERSION,
+               .prefix = "samba4:",
+               .create = hdb_samba4_create
+       };
 
        switch (lp_server_role(task->lp_ctx)) {
        case ROLE_STANDALONE:
@@ -724,7 +729,7 @@ static void kdc_task_init(struct task_server *task)
        }
        kdc->config->num_db = 1;
                
-       status = kdc_hdb_ldb_create(kdc, task->event_ctx, task->lp_ctx, 
+       status = kdc_hdb_samba4_create(kdc, task->event_ctx, task->lp_ctx, 
                                    kdc->smb_krb5_context->krb5_context, 
                                    &kdc->config->db[0], NULL);
        if (!NT_STATUS_IS_OK(status)) {
@@ -732,6 +737,16 @@ static void kdc_task_init(struct task_server *task)
                return; 
        }
 
+
+       /* Register hdb-samba4 hooks */
+       ret = krb5_plugin_register(kdc->smb_krb5_context->krb5_context, 
+                                  PLUGIN_TYPE_DATA, "hdb",
+                                  &hdb_samba4);
+       if(ret) {
+               task_server_terminate(task, "kdc: failed to register hdb keytab");
+               return;
+       }
+
        ret = krb5_kt_register(kdc->smb_krb5_context->krb5_context, &hdb_kt_ops);
        if(ret) {
                task_server_terminate(task, "kdc: failed to register hdb keytab");
index b954038b8046502489c9db3a7564c95925a394f4..ffbef3d92fe9dbb0a9b117dbb028bd566be4009d 100644 (file)
@@ -158,6 +158,8 @@ static NTSTATUS ldapsrv_SearchRequest(struct ldapsrv_call *call)
        struct ldb_dn *basedn;
        struct ldb_result *res = NULL;
        struct ldb_request *lreq;
+       struct ldb_control *search_control;
+       struct ldb_search_options_control *search_options;
        enum ldb_scope scope = LDB_SCOPE_DEFAULT;
        const char **attrs = NULL;
        const char *scope_str, *errstr = NULL;
@@ -216,21 +218,24 @@ static NTSTATUS ldapsrv_SearchRequest(struct ldapsrv_call *call)
        DEBUG(5,("ldb_request %s dn=%s filter=%s\n", 
                 scope_str, req->basedn, ldb_filter_from_tree(call, req->tree)));
 
-       lreq = talloc(local_ctx, struct ldb_request);
-       NT_STATUS_HAVE_NO_MEMORY(lreq);
+       res = talloc_zero(local_ctx, struct ldb_result);
+       NT_STATUS_HAVE_NO_MEMORY(res);
 
-       lreq->operation = LDB_SEARCH;
-       lreq->op.search.base = basedn;
-       lreq->op.search.scope = scope;
-       lreq->op.search.tree = req->tree;
-       lreq->op.search.attrs = attrs;
+       ldb_ret = ldb_build_search_req_ex(&lreq, samdb, local_ctx,
+                                         basedn, scope,
+                                         req->tree, attrs,
+                                         call->request->controls,
+                                         res, ldb_search_default_callback,
+                                         NULL);
 
-       lreq->controls = call->request->controls;
+       if (ldb_ret != LDB_SUCCESS) {
+               goto reply;
+       }
 
        if (call->conn->global_catalog) {
-               struct ldb_control *search_control = ldb_request_get_control(lreq, LDB_CONTROL_SEARCH_OPTIONS_OID);
-               
-               struct ldb_search_options_control *search_options = NULL;
+               search_control = ldb_request_get_control(lreq, LDB_CONTROL_SEARCH_OPTIONS_OID);
+
+               search_options = NULL;
                if (search_control) {
                        search_options = talloc_get_type(search_control->data, struct ldb_search_options_control);
                        search_options->search_options |= LDB_SEARCH_OPTION_PHANTOM_ROOT;
@@ -241,14 +246,6 @@ static NTSTATUS ldapsrv_SearchRequest(struct ldapsrv_call *call)
                        ldb_request_add_control(lreq, LDB_CONTROL_SEARCH_OPTIONS_OID, false, search_options);
                }
        }
-
-       res = talloc_zero(lreq, struct ldb_result);
-       NT_STATUS_HAVE_NO_MEMORY(res);
-       
-       lreq->context = res;
-       lreq->callback = ldb_search_default_callback;
-
-       /* Copy the timeout from the incoming call */
        ldb_set_timeout(samdb, lreq, req->timelimit);
 
        ldb_ret = ldb_request(samdb, lreq);
index a8ff88423a27adce45101501ea1553bf479a7df0..5f3b2c53f120c9ebefde45211ecb7021dc52b983 100644 (file)
@@ -386,6 +386,9 @@ _PUBLIC_ size_t strlen_m_term(const char *s)
 **/
 _PUBLIC_ char *strchr_m(const char *s, char c)
 {
+       if (s == NULL) {
+               return NULL;
+       }
        /* characters below 0x3F are guaranteed to not appear in
           non-initial position in multi-byte charsets */
        if ((c & 0xC0) == 0) {
@@ -411,6 +414,10 @@ _PUBLIC_ char *strrchr_m(const char *s, char c)
 {
        char *ret = NULL;
 
+       if (s == NULL) {
+               return NULL;
+       }
+
        /* characters below 0x3F are guaranteed to not appear in
           non-initial position in multi-byte charsets */
        if ((c & 0xC0) == 0) {
index 3b73947b76b2fdce44ed579cb7cf389d07613549..75c8109042a3e05d334664e20b160db33ceabdee 100644 (file)
@@ -193,9 +193,6 @@ int ldb_connect(struct ldb_context *ldb, const char *url,
                return LDB_ERR_OTHER;
        }
 
-       /* TODO: get timeout from options if available there */
-       ldb->default_timeout = 300; /* set default to 5 minutes */
-
        /* set the default base dn */
        ldb_set_default_dns(ldb);
 
@@ -396,24 +393,44 @@ static int ldb_autotransaction_request(struct ldb_context *ldb,
 
 int ldb_wait(struct ldb_handle *handle, enum ldb_wait_type type)
 {
-       int ret;
+       struct event_context *ev;
+
        if (!handle) {
-               return LDB_SUCCESS;
+               return LDB_ERR_UNAVAILABLE;
        }
 
-       ret = handle->module->ops->wait(handle, type);
-       if (!ldb_errstring(handle->module->ldb)) {
-               /* Set a default error string, to place the blame somewhere */
-               ldb_asprintf_errstring(handle->module->ldb,
-                                       "error waiting on module %s: %s (%d)",
-                                       handle->module->ops->name,
-                                       ldb_strerror(ret), ret);
+       if (handle->state == LDB_ASYNC_DONE) {
+               return handle->status;
        }
-       return ret;
+
+       ev = ldb_get_event_context(handle->ldb);
+       if (NULL == ev) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       switch (type) {
+       case LDB_WAIT_NONE:
+               event_loop_once(ev);
+               if (handle->state == LDB_ASYNC_DONE ||
+                   handle->status != LDB_SUCCESS) {
+                       return handle->status;
+               }
+               break;
+
+       case LDB_WAIT_ALL:
+               while (handle->state != LDB_ASYNC_DONE) {
+                       event_loop_once(ev);
+                       if (handle->status != LDB_SUCCESS) {
+                               return handle->status;
+                       }
+               }
+               return handle->status;
+       }
+
+       return LDB_SUCCESS;
 }
 
 /* set the specified timeout or, if timeout is 0 set the default timeout */
-/* timeout == -1 means no timeout */
 int ldb_set_timeout(struct ldb_context *ldb,
                    struct ldb_request *req,
                    int timeout)
@@ -435,20 +452,14 @@ int ldb_set_timeout_from_prev_req(struct ldb_context *ldb,
                                  struct ldb_request *oldreq,
                                  struct ldb_request *newreq)
 {
-       time_t now;
-
        if (newreq == NULL) return LDB_ERR_OPERATIONS_ERROR;
 
-       now = time(NULL);
-
-       if (oldreq == NULL)
+       if (oldreq == NULL) {
                return ldb_set_timeout(ldb, newreq, 0);
-
-       if ((now - oldreq->starttime) > oldreq->timeout) {
-               return LDB_ERR_TIME_LIMIT_EXCEEDED;
        }
+
        newreq->starttime = oldreq->starttime;
-       newreq->timeout = oldreq->timeout - (now - oldreq->starttime);
+       newreq->timeout = oldreq->timeout;
 
        return LDB_SUCCESS;
 }
@@ -483,6 +494,11 @@ int ldb_request(struct ldb_context *ldb, struct ldb_request *req)
        struct ldb_module *module;
        int ret;
 
+       if (req->callback == NULL) {
+               ldb_set_errstring(ldb, "Requests MUST define callbacks");
+               return LDB_ERR_UNWILLING_TO_PERFORM;
+       }
+
        ldb_reset_err_string(ldb);
 
        /* call the first module in the chain */
@@ -524,6 +540,13 @@ int ldb_request(struct ldb_context *ldb, struct ldb_request *req)
        return ret;
 }
 
+int ldb_request_done(struct ldb_request *req, int status)
+{
+       req->handle->state = LDB_ASYNC_DONE;
+       req->handle->status = status;
+       return status;
+}
+
 /*
   search the database given a LDAP-like search expression
 
@@ -532,32 +555,27 @@ int ldb_request(struct ldb_context *ldb, struct ldb_request *req)
   Use talloc_free to free the ldb_message returned in 'res', if successful
 
 */
-int ldb_search_default_callback(struct ldb_context *ldb,
-                               void *context,
+int ldb_search_default_callback(struct ldb_request *req,
                                struct ldb_reply *ares)
 {
        struct ldb_result *res;
        int n;
 
-       if (!context) {
-               ldb_set_errstring(ldb, "NULL Context in callback");
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
+       res = talloc_get_type(req->context, struct ldb_result);
 
-       res = talloc_get_type(context, struct ldb_result);
-
-       if (!res || !ares) {
-               ldb_set_errstring(ldb, "NULL res or ares in callback");
-               goto error;
+       if (!ares) {
+               return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_request_done(req, ares->error);
        }
 
        switch (ares->type) {
        case LDB_REPLY_ENTRY:
                res->msgs = talloc_realloc(res, res->msgs,
-                                          struct ldb_message *,
-                                          res->count + 2);
+                                       struct ldb_message *, res->count + 2);
                if (! res->msgs) {
-                       goto error;
+                       return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
                }
 
                res->msgs[res->count + 1] = NULL;
@@ -565,6 +583,7 @@ int ldb_search_default_callback(struct ldb_context *ldb,
                res->msgs[res->count] = talloc_move(res->msgs, &ares->message);
                res->count++;
                break;
+
        case LDB_REPLY_REFERRAL:
                if (res->refs) {
                        for (n = 0; res->refs[n]; n++) /*noop*/ ;
@@ -574,37 +593,63 @@ int ldb_search_default_callback(struct ldb_context *ldb,
 
                res->refs = talloc_realloc(res, res->refs, char *, n + 2);
                if (! res->refs) {
-                       goto error;
+                       return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
                }
 
                res->refs[n] = talloc_move(res->refs, &ares->referral);
                res->refs[n + 1] = NULL;
                break;
-       case LDB_REPLY_EXTENDED:
+
        case LDB_REPLY_DONE:
                /* TODO: we should really support controls on entries
                 * and referrals too! */
                res->controls = talloc_move(res, &ares->controls);
-               break;
+
+               /* this is the last message, and means the request is done */
+               /* we have to signal and eventual ldb_wait() waiting that the
+                * async request operation was completed */
+               return ldb_request_done(req, LDB_SUCCESS);
        }
+
        talloc_free(ares);
        return LDB_SUCCESS;
+}
+
+int ldb_op_default_callback(struct ldb_request *req, struct ldb_reply *ares)
+{
+       int ret;
+
+       if (!ares) {
+               return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
+       }
+
+       if (ares->error != LDB_SUCCESS) {
+               ret = ares->error;
+               talloc_free(ares);
+               return ldb_request_done(req, ret);
+       }
+
+       if (ares->type != LDB_REPLY_DONE) {
+               talloc_free(ares);
+               ldb_set_errstring(req->handle->ldb, "Invalid reply type!");
+               return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
+       }
 
-error:
        talloc_free(ares);
-       return LDB_ERR_OPERATIONS_ERROR;
+       return ldb_request_done(req, LDB_SUCCESS);
 }
 
-int ldb_build_search_req(struct ldb_request **ret_req,
+int ldb_build_search_req_ex(struct ldb_request **ret_req,
                        struct ldb_context *ldb,
                        void *mem_ctx,
                        struct ldb_dn *base,
                        enum ldb_scope scope,
-                       const char *expression,
+                       struct ldb_parse_tree *tree,
                        const char * const *attrs,
                        struct ldb_control **controls,
                        void *context,
-                       ldb_request_callback_t callback)
+                       ldb_request_callback_t callback,
+                       struct ldb_request *parent)
 {
        struct ldb_request *req;
 
@@ -612,7 +657,7 @@ int ldb_build_search_req(struct ldb_request **ret_req,
 
        req = talloc(mem_ctx, struct ldb_request);
        if (req == NULL) {
-               ldb_set_errstring(ldb, "Out of Memory");
+               ldb_oom(ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
@@ -624,9 +669,9 @@ int ldb_build_search_req(struct ldb_request **ret_req,
        }
        req->op.search.scope = scope;
 
-       req->op.search.tree = ldb_parse_tree(req, expression);
+       req->op.search.tree = tree;
        if (req->op.search.tree == NULL) {
-               ldb_set_errstring(ldb, "Unable to parse search expression");
+               ldb_set_errstring(ldb, "'tree' can't be NULL");
                talloc_free(req);
                return LDB_ERR_OPERATIONS_ERROR;
        }
@@ -636,17 +681,56 @@ int ldb_build_search_req(struct ldb_request **ret_req,
        req->context = context;
        req->callback = callback;
 
+       ldb_set_timeout_from_prev_req(ldb, parent, req);
+
+       req->handle = ldb_handle_new(req, ldb);
+       if (req->handle == NULL) {
+               ldb_oom(ldb);
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
        *ret_req = req;
        return LDB_SUCCESS;
 }
 
+int ldb_build_search_req(struct ldb_request **ret_req,
+                       struct ldb_context *ldb,
+                       void *mem_ctx,
+                       struct ldb_dn *base,
+                       enum ldb_scope scope,
+                       const char *expression,
+                       const char * const *attrs,
+                       struct ldb_control **controls,
+                       void *context,
+                       ldb_request_callback_t callback,
+                       struct ldb_request *parent)
+{
+       struct ldb_parse_tree *tree;
+       int ret;
+
+       tree = ldb_parse_tree(mem_ctx, expression);
+       if (tree == NULL) {
+               ldb_set_errstring(ldb, "Unable to parse search expression");
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       ret = ldb_build_search_req_ex(ret_req, ldb, mem_ctx, base,
+                                     scope, tree, attrs, controls,
+                                     context, callback, parent);
+       if (ret == LDB_SUCCESS) {
+               talloc_steal(*ret_req, tree);
+       }
+       return ret;
+}
+
 int ldb_build_add_req(struct ldb_request **ret_req,
                        struct ldb_context *ldb,
                        void *mem_ctx,
                        const struct ldb_message *message,
                        struct ldb_control **controls,
                        void *context,
-                       ldb_request_callback_t callback)
+                       ldb_request_callback_t callback,
+                       struct ldb_request *parent)
 {
        struct ldb_request *req;
 
@@ -664,6 +748,14 @@ int ldb_build_add_req(struct ldb_request **ret_req,
        req->context = context;
        req->callback = callback;
 
+       ldb_set_timeout_from_prev_req(ldb, parent, req);
+
+       req->handle = ldb_handle_new(req, ldb);
+       if (req->handle == NULL) {
+               ldb_oom(ldb);
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
        *ret_req = req;
 
        return LDB_SUCCESS;
@@ -675,7 +767,8 @@ int ldb_build_mod_req(struct ldb_request **ret_req,
                        const struct ldb_message *message,
                        struct ldb_control **controls,
                        void *context,
-                       ldb_request_callback_t callback)
+                       ldb_request_callback_t callback,
+                       struct ldb_request *parent)
 {
        struct ldb_request *req;
 
@@ -693,6 +786,14 @@ int ldb_build_mod_req(struct ldb_request **ret_req,
        req->context = context;
        req->callback = callback;
 
+       ldb_set_timeout_from_prev_req(ldb, parent, req);
+
+       req->handle = ldb_handle_new(req, ldb);
+       if (req->handle == NULL) {
+               ldb_oom(ldb);
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
        *ret_req = req;
 
        return LDB_SUCCESS;
@@ -704,7 +805,8 @@ int ldb_build_del_req(struct ldb_request **ret_req,
                        struct ldb_dn *dn,
                        struct ldb_control **controls,
                        void *context,
-                       ldb_request_callback_t callback)
+                       ldb_request_callback_t callback,
+                       struct ldb_request *parent)
 {
        struct ldb_request *req;
 
@@ -722,6 +824,14 @@ int ldb_build_del_req(struct ldb_request **ret_req,
        req->context = context;
        req->callback = callback;
 
+       ldb_set_timeout_from_prev_req(ldb, parent, req);
+
+       req->handle = ldb_handle_new(req, ldb);
+       if (req->handle == NULL) {
+               ldb_oom(ldb);
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
        *ret_req = req;
 
        return LDB_SUCCESS;
@@ -734,7 +844,8 @@ int ldb_build_rename_req(struct ldb_request **ret_req,
                        struct ldb_dn *newdn,
                        struct ldb_control **controls,
                        void *context,
-                       ldb_request_callback_t callback)
+                       ldb_request_callback_t callback,
+                       struct ldb_request *parent)
 {
        struct ldb_request *req;
 
@@ -753,47 +864,46 @@ int ldb_build_rename_req(struct ldb_request **ret_req,
        req->context = context;
        req->callback = callback;
 
+       ldb_set_timeout_from_prev_req(ldb, parent, req);
+
+       req->handle = ldb_handle_new(req, ldb);
+       if (req->handle == NULL) {
+               ldb_oom(ldb);
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
        *ret_req = req;
 
        return LDB_SUCCESS;
 }
 
-int ldb_extended_default_callback(struct ldb_context *ldb,
-                                 void *context,
+int ldb_extended_default_callback(struct ldb_request *req,
                                  struct ldb_reply *ares)
 {
        struct ldb_result *res;
 
-       if (!context) {
-               ldb_set_errstring(ldb, "NULL Context in callback");
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
+       res = talloc_get_type(req->context, struct ldb_result);
 
-       res = talloc_get_type(context, struct ldb_result);
-       if (!res || !ares) {
-               ldb_set_errstring(ldb, "NULL res or ares in callback");
-               goto error;
+       if (!ares) {
+               return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_request_done(req, ares->error);
        }
 
-       switch (ares->type) {
-       case LDB_REPLY_ENTRY:
-       case LDB_REPLY_REFERRAL:
-       case LDB_REPLY_DONE:
-               ldb_set_errstring(ldb, "invalid ares type in callback");
-               goto error;
-       case LDB_REPLY_EXTENDED:
-               /* TODO: we should really support controls on entries and
-                * referrals too! */
+       if (ares->type == LDB_REPLY_DONE) {
+
+               /* TODO: we should really support controls on entries and referrals too! */
                res->extended = talloc_move(res, &ares->response);
                res->controls = talloc_move(res, &ares->controls);
-               break;
+
+               talloc_free(ares);
+               return ldb_request_done(req, LDB_SUCCESS);
        }
-       talloc_free(ares);
-       return LDB_SUCCESS;
 
-error:
        talloc_free(ares);
-       return LDB_ERR_OPERATIONS_ERROR;
+       ldb_set_errstring(req->handle->ldb, "Invalid reply type!");
+       return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
 }
 
 int ldb_build_extended_req(struct ldb_request **ret_req,
@@ -803,7 +913,8 @@ int ldb_build_extended_req(struct ldb_request **ret_req,
                           void *data,
                           struct ldb_control **controls,
                           void *context,
-                          ldb_request_callback_t callback)
+                          ldb_request_callback_t callback,
+                          struct ldb_request *parent)
 {
        struct ldb_request *req;
 
@@ -822,6 +933,14 @@ int ldb_build_extended_req(struct ldb_request **ret_req,
        req->context = context;
        req->callback = callback;
 
+       ldb_set_timeout_from_prev_req(ldb, parent, req);
+
+       req->handle = ldb_handle_new(req, ldb);
+       if (req->handle == NULL) {
+               ldb_oom(ldb);
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
        *ret_req = req;
 
        return LDB_SUCCESS;
@@ -845,7 +964,8 @@ int ldb_extended(struct ldb_context *ldb,
 
        ret = ldb_build_extended_req(&req, ldb, ldb,
                                     oid, data, NULL,
-                                    res, ldb_extended_default_callback);
+                                    res, ldb_extended_default_callback,
+                                    NULL);
        if (ret != LDB_SUCCESS) goto done;
 
        ldb_set_timeout(ldb, req, 0); /* use default timeout */
@@ -909,12 +1029,11 @@ int ldb_search(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
                                        attrs,
                                        NULL,
                                        res,
-                                       ldb_search_default_callback);
+                                       ldb_search_default_callback,
+                                       NULL);
 
        if (ret != LDB_SUCCESS) goto done;
 
-       ldb_set_timeout(ldb, req, 0); /* use default timeout */
-
        ret = ldb_request(ldb, req);
 
        if (ret == LDB_SUCCESS) {
@@ -935,8 +1054,8 @@ done:
 }
 
 /*
-  add a record to the database. Will fail if a record with the
-  given class and key already exists
+  add a record to the database. Will fail if a record with the given class
+  and key already exists
 */
 int ldb_add(struct ldb_context *ldb,
            const struct ldb_message *message)
@@ -953,12 +1072,11 @@ int ldb_add(struct ldb_context *ldb,
                                        message,
                                        NULL,
                                        NULL,
+                                       ldb_op_default_callback,
                                        NULL);
 
        if (ret != LDB_SUCCESS) return ret;
 
-       ldb_set_timeout(ldb, req, 0); /* use default timeout */
-
        /* do request and autostart a transaction */
        ret = ldb_autotransaction_request(ldb, req);
 
@@ -984,12 +1102,11 @@ int ldb_modify(struct ldb_context *ldb,
                                        message,
                                        NULL,
                                        NULL,
+                                       ldb_op_default_callback,
                                        NULL);
 
        if (ret != LDB_SUCCESS) return ret;
 
-       ldb_set_timeout(ldb, req, 0); /* use default timeout */
-
        /* do request and autostart a transaction */
        ret = ldb_autotransaction_request(ldb, req);
 
@@ -1010,12 +1127,11 @@ int ldb_delete(struct ldb_context *ldb, struct ldb_dn *dn)
                                        dn,
                                        NULL,
                                        NULL,
+                                       ldb_op_default_callback,
                                        NULL);
 
        if (ret != LDB_SUCCESS) return ret;
 
-       ldb_set_timeout(ldb, req, 0); /* use default timeout */
-
        /* do request and autostart a transaction */
        ret = ldb_autotransaction_request(ldb, req);
 
@@ -1037,12 +1153,11 @@ int ldb_rename(struct ldb_context *ldb,
                                        newdn,
                                        NULL,
                                        NULL,
+                                       ldb_op_default_callback,
                                        NULL);
 
        if (ret != LDB_SUCCESS) return ret;
 
-       ldb_set_timeout(ldb, req, 0); /* use default timeout */
-
        /* do request and autostart a transaction */
        ret = ldb_autotransaction_request(ldb, req);
 
@@ -1055,13 +1170,12 @@ int ldb_rename(struct ldb_context *ldb,
   return the global sequence number
 */
 int ldb_sequence_number(struct ldb_context *ldb,
-                       enum ldb_sequence_type type,
-                       uint64_t *seq_num)
+                       enum ldb_sequence_type type, uint64_t *seq_num)
 {
        struct ldb_request *req;
        int ret;
 
-       req = talloc(ldb, struct ldb_request);
+       req = talloc_zero(ldb, struct ldb_request);
        if (req == NULL) {
                ldb_set_errstring(ldb, "Out of Memory");
                return LDB_ERR_OPERATIONS_ERROR;
@@ -1070,7 +1184,7 @@ int ldb_sequence_number(struct ldb_context *ldb,
        req->operation = LDB_SEQUENCE_NUMBER;
        req->controls = NULL;
        req->context = NULL;
-       req->callback = NULL;
+       req->callback = ldb_op_default_callback;
        ldb_set_timeout(ldb, req, 0); /* use default timeout */
 
        req->op.seq_num.type = type;
index c0d36cfbf3e0c48239b123a8920fbd4d065cc068..e36aea4e697fd8b2dddf5bdfdcaad64d18aa7c2a 100644 (file)
@@ -91,7 +91,7 @@ struct ldb_dn *ldb_dn_from_ldb_val(void *mem_ctx, struct ldb_context *ldb, const
                         * exploded_dn control is used */
                        dn->special = true;
                        /* FIXME: add a GUID string to ldb_dn structure */
-               } else if (strdn->length >= 8 && strncasecmp((const char *)strdn->data, "<SID=", 8) == 0) {
+               } else if (strdn->length >= 5 && strncasecmp((const char *)strdn->data, "<SID=", 5) == 0) {
                        /* this is special DN returned when the
                         * exploded_dn control is used */
                        dn->special = true;
@@ -150,7 +150,7 @@ struct ldb_dn *ldb_dn_new_fmt(void *mem_ctx, struct ldb_context *ldb, const char
                 * exploded_dn control is used */
                dn->special = true;
                /* FIXME: add a GUID string to ldb_dn structure */
-       } else if (strncasecmp(strdn, "<SID=", 8) == 0) {
+       } else if (strncasecmp(strdn, "<SID=", 5) == 0) {
                /* this is special DN returned when the
                 * exploded_dn control is used */
                dn->special = true;
index c0cd616a76e63bb02f1530b2de2d729d09b08264..5cc8de29b4851ef671a2f68599f02eb21e0e23b7 100644 (file)
@@ -1,7 +1,7 @@
 /* 
    ldb database library
 
-   Copyright (C) Simo Sorce  2004
+   Copyright (C) Simo Sorce  2004-2008
 
      ** NOTE! The following LGPL license applies to the ldb
      ** library. This does NOT imply that all of Samba is released
@@ -486,6 +486,12 @@ int ldb_load_modules(struct ldb_context *ldb, const char *options[])
 int ldb_next_request(struct ldb_module *module, struct ldb_request *request)
 {
        int ret;
+
+       if (request->callback == NULL) {
+               ldb_set_errstring(module->ldb, "Requests MUST define callbacks");
+               return LDB_ERR_UNWILLING_TO_PERFORM;
+       }
+
        switch (request->operation) {
        case LDB_SEARCH:
                FIND_OP(module, search);
@@ -555,6 +561,139 @@ int ldb_next_del_trans(struct ldb_module *module)
        return module->ops->del_transaction(module);
 }
 
+struct ldb_handle *ldb_handle_new(TALLOC_CTX *mem_ctx, struct ldb_context *ldb)
+{
+       struct ldb_handle *h;
+
+       h = talloc_zero(mem_ctx, struct ldb_handle);
+       if (h == NULL) {
+               ldb_set_errstring(ldb, "Out of Memory");
+               return NULL;
+       }
+
+       h->status = LDB_SUCCESS;
+       h->state = LDB_ASYNC_INIT;
+       h->ldb = ldb;
+
+       return h;
+}
+
+/* calls the request callback to send an entry
+ *
+ * params:
+ *      req: the original request passed to your module
+ *      msg: reply message (must be a talloc pointer, and it will be stolen
+ *           on the ldb_reply that is sent to the callback)
+ */
+
+int ldb_module_send_entry(struct ldb_request *req,
+                         struct ldb_message *msg)
+{
+       struct ldb_reply *ares;
+
+       ares = talloc_zero(req, struct ldb_reply);
+       if (!ares) {
+               ldb_oom(req->handle->ldb);
+               req->callback(req, NULL);
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+       ares->type = LDB_REPLY_ENTRY;
+       ares->message = talloc_steal(ares, msg);
+       ares->error = LDB_SUCCESS;
+
+       return req->callback(req, ares);
+}
+
+/* calls the request callback to send an referrals
+ *
+ * params:
+ *      req: the original request passed to your module
+ *      ref: referral string (must be a talloc pointeri, steal)
+ */
+
+int ldb_module_send_referral(struct ldb_request *req,
+                                          char *ref)
+{
+       struct ldb_reply *ares;
+
+       ares = talloc_zero(req, struct ldb_reply);
+       if (!ares) {
+               ldb_oom(req->handle->ldb);
+               req->callback(req, NULL);
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+       ares->type = LDB_REPLY_REFERRAL;
+       ares->referral = talloc_steal(ares, ref);
+       ares->error = LDB_SUCCESS;
+
+       return req->callback(req, ares);
+}
+
+/* calls the original request callback
+ *
+ * params:
+ *     req:   the original request passed to your module
+ *     ctrls: controls to send in the reply (must be a talloc pointer, steal)
+ *     response: results for extended request (steal)
+ *     error: LDB_SUCCESS for a succesful return
+ *            any other ldb error otherwise
+ */
+int ldb_module_done(struct ldb_request *req,
+                   struct ldb_control **ctrls,
+                   struct ldb_extended *response,
+                   int error)
+{
+       struct ldb_reply *ares;
+
+       ares = talloc_zero(req, struct ldb_reply);
+       if (!ares) {
+               ldb_oom(req->handle->ldb);
+               req->callback(req, NULL);
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+       ares->type = LDB_REPLY_DONE;
+       ares->controls = talloc_steal(ares, ctrls);
+       ares->response = talloc_steal(ares, response);
+       ares->error = error;
+
+       req->callback(req, ares);
+       return error;
+}
+
+/* to be used *only* in modules init functions.
+ * this function i synchronous and will register
+ * the requested OID in the rootdse module if present
+ * otherwise it will return an error */
+int ldb_mod_register_control(struct ldb_module *module, const char *oid)
+{
+       struct ldb_request *req;
+       int ret;
+
+       req = talloc_zero(module, struct ldb_request);
+       if (req == NULL) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       req->operation = LDB_REQ_REGISTER_CONTROL;
+       req->op.reg_control.oid = oid;
+       req->callback = ldb_op_default_callback;
+
+       ldb_set_timeout(module->ldb, req, 0);
+
+       req->handle = ldb_handle_new(req, module->ldb);
+       if (req->handle == NULL) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       ret = ldb_request(module->ldb, req);
+       if (ret == LDB_SUCCESS) {
+               ret = ldb_wait(req->handle, LDB_WAIT_ALL);
+       }
+       talloc_free(req);
+
+       return ret;
+}
+
 #ifndef STATIC_LIBLDB_MODULES
 
 #ifdef HAVE_LDB_LDAP
index 645d7866c52677163cfc96a71d65187393715308..b1ce3ef70b2a7073a65b6cad98bc59cc49566abd 100644 (file)
@@ -181,6 +181,7 @@ enum ldb_scope {LDB_SCOPE_DEFAULT=-1,
                LDB_SCOPE_SUBTREE=2};
 
 struct ldb_context;
+struct event_context;
 
 /* debugging uses one of the following levels */
 enum ldb_debug_level {LDB_DEBUG_FATAL, LDB_DEBUG_ERROR, 
@@ -659,7 +660,6 @@ enum ldb_request_type {
 enum ldb_reply_type {
        LDB_REPLY_ENTRY,
        LDB_REPLY_REFERRAL,
-       LDB_REPLY_EXTENDED,
        LDB_REPLY_DONE
 };
 
@@ -693,14 +693,11 @@ struct ldb_reply {
        struct ldb_extended *response;
        char *referral;
        struct ldb_control **controls;
+       int error;
 };
 
-struct ldb_handle {
-       int status;
-       enum ldb_state state;
-       void *private_data;
-       struct ldb_module *module;
-};
+struct ldb_request;
+struct ldb_handle;
 
 struct ldb_search {
        struct ldb_dn *base;
@@ -747,7 +744,8 @@ struct ldb_sequence_number {
        uint32_t flags;
 };
 
-typedef int (*ldb_request_callback_t)(struct ldb_context *, void *, struct ldb_reply *);
+typedef int (*ldb_request_callback_t)(struct ldb_request *, struct ldb_reply *);
+
 struct ldb_request {
 
        enum ldb_request_type operation;
@@ -775,7 +773,10 @@ struct ldb_request {
 };
 
 int ldb_request(struct ldb_context *ldb, struct ldb_request *request);
+int ldb_request_done(struct ldb_request *req, int status);
+bool ldb_request_is_done(struct ldb_request *req);
 
+int ldb_modules_wait(struct ldb_handle *handle);
 int ldb_wait(struct ldb_handle *handle, enum ldb_wait_type type);
 
 int ldb_set_timeout(struct ldb_context *ldb, struct ldb_request *req, int timeout);
@@ -831,6 +832,19 @@ struct ldb_context *ldb_init(TALLOC_CTX *mem_ctx, struct event_context *ev_ctx);
    (that is, with LDB_FLG_RDONLY). However in read-write mode, the database will be
    created if it does not exist.
 */
+
+typedef void (*ldb_async_timeout_fn) (void *);
+typedef bool (*ldb_async_callback_fn) (void *);
+typedef int (*ldb_async_ctx_add_op_fn)(void *, time_t, void *, ldb_async_timeout_fn, ldb_async_callback_fn);
+typedef int (*ldb_async_ctx_wait_op_fn)(void *);
+
+void ldb_async_ctx_set_private_data(struct ldb_context *ldb,
+                                       void *private_data);
+void ldb_async_ctx_set_add_op(struct ldb_context *ldb,
+                               ldb_async_ctx_add_op_fn add_op);
+void ldb_async_ctx_set_wait_op(struct ldb_context *ldb,
+                               ldb_async_ctx_wait_op_fn wait_op);
+
 int ldb_connect(struct ldb_context *ldb, const char *url, unsigned int flags, const char *options[]);
 
 /*
@@ -860,13 +874,12 @@ struct ldb_dn *ldb_get_default_basedn(struct ldb_context *ldb);
 /**
   The default async search callback function 
 
-  \param ldb the context associated with the database (from ldb_init())
-  \param context the callback context (struct ldb_result *)
+  \param req the request we are callback of
   \param ares a single reply from the async core
 
   \return result code (LDB_SUCCESS on success, or a failure code)
 
-  \note this function expects the context to always be an struct ldb_result pointer
+  \note this function expects req->context to always be an struct ldb_result pointer
   AND a talloc context, this function will steal on the context each message
   from the ares reply passed on by the async core so that in the end all the
   messages will be in the context (ldb_result)  memory tree.
@@ -875,7 +888,18 @@ struct ldb_dn *ldb_get_default_basedn(struct ldb_context *ldb);
   request that can be freed as sson as the search request is finished)
 */
 
-int ldb_search_default_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares);
+int ldb_search_default_callback(struct ldb_request *req, struct ldb_reply *ares);
+
+/**
+  The default async extended operation callback function
+
+  \param req the request we are callback of
+  \param ares a single reply from the async core
+
+  \return result code (LDB_SUCCESS on success, or a failure code)
+*/
+int ldb_op_default_callback(struct ldb_request *req, struct ldb_reply *ares);
+
 
 /**
   Helper function to build a search request
@@ -889,7 +913,8 @@ int ldb_search_default_callback(struct ldb_context *ldb, void *context, struct l
   \param attrs the search attributes for the query (pass NULL if none required)
   \param controls an array of controls
   \param context the callback function context
-  \param callback the callback function to handle the async replies
+  \param the callback function to handle the async replies
+  \param the parent request if any
 
   \return result code (LDB_SUCCESS on success, or a failure code)
 */
@@ -903,7 +928,20 @@ int ldb_build_search_req(struct ldb_request **ret_req,
                        const char * const *attrs,
                        struct ldb_control **controls,
                        void *context,
-                       ldb_request_callback_t callback);
+                       ldb_request_callback_t callback,
+                       struct ldb_request *parent);
+
+int ldb_build_search_req_ex(struct ldb_request **ret_req,
+                       struct ldb_context *ldb,
+                       TALLOC_CTX *mem_ctx,
+                       struct ldb_dn *base,
+                       enum ldb_scope scope,
+                       struct ldb_parse_tree *tree,
+                       const char * const *attrs,
+                       struct ldb_control **controls,
+                       void *context,
+                       ldb_request_callback_t callback,
+                       struct ldb_request *parent);
 
 /**
   Helper function to build an add request
@@ -914,7 +952,8 @@ int ldb_build_search_req(struct ldb_request **ret_req,
   \param message contains the entry to be added 
   \param controls an array of controls
   \param context the callback function context
-  \param callback the callback function to handle the async replies
+  \param the callback function to handle the async replies
+  \param the parent request if any
 
   \return result code (LDB_SUCCESS on success, or a failure code)
 */
@@ -925,7 +964,8 @@ int ldb_build_add_req(struct ldb_request **ret_req,
                        const struct ldb_message *message,
                        struct ldb_control **controls,
                        void *context,
-                       ldb_request_callback_t callback);
+                       ldb_request_callback_t callback,
+                       struct ldb_request *parent);
 
 /**
   Helper function to build a modify request
@@ -936,7 +976,8 @@ int ldb_build_add_req(struct ldb_request **ret_req,
   \param message contains the entry to be modified
   \param controls an array of controls
   \param context the callback function context
-  \param callback the callback function to handle the async replies
+  \param the callback function to handle the async replies
+  \param the parent request if any
 
   \return result code (LDB_SUCCESS on success, or a failure code)
 */
@@ -947,7 +988,8 @@ int ldb_build_mod_req(struct ldb_request **ret_req,
                        const struct ldb_message *message,
                        struct ldb_control **controls,
                        void *context,
-                       ldb_request_callback_t callback);
+                       ldb_request_callback_t callback,
+                       struct ldb_request *parent);
 
 /**
   Helper function to build a delete request
@@ -958,7 +1000,8 @@ int ldb_build_mod_req(struct ldb_request **ret_req,
   \param dn the DN to be deleted
   \param controls an array of controls
   \param context the callback function context
-  \param callback the callback function to handle the async replies
+  \param the callback function to handle the async replies
+  \param the parent request if any
 
   \return result code (LDB_SUCCESS on success, or a failure code)
 */
@@ -969,7 +1012,8 @@ int ldb_build_del_req(struct ldb_request **ret_req,
                        struct ldb_dn *dn,
                        struct ldb_control **controls,
                        void *context,
-                       ldb_request_callback_t callback);
+                       ldb_request_callback_t callback,
+                       struct ldb_request *parent);
 
 /**
   Helper function to build a rename request
@@ -981,7 +1025,8 @@ int ldb_build_del_req(struct ldb_request **ret_req,
   \param newdn the new DN
   \param controls an array of controls
   \param context the callback function context
-  \param callback the callback function to handle the async replies
+  \param the callback function to handle the async replies
+  \param the parent request if any
 
   \return result code (LDB_SUCCESS on success, or a failure code)
 */
@@ -993,7 +1038,8 @@ int ldb_build_rename_req(struct ldb_request **ret_req,
                        struct ldb_dn *newdn,
                        struct ldb_control **controls,
                        void *context,
-                       ldb_request_callback_t callback);
+                       ldb_request_callback_t callback,
+                       struct ldb_request *parent);
 
 /**
   Add a ldb_control to a ldb_request
@@ -1103,13 +1149,12 @@ int ldb_delete(struct ldb_context *ldb, struct ldb_dn *dn);
 /**
   The default async extended operation callback function 
 
-  \param ldb the context associated with the database (from ldb_init())
-  \param context the callback context (struct ldb_result *)
+  \param req the request we are callback of
   \param ares a single reply from the async core
 
   \return result code (LDB_SUCCESS on success, or a failure code)
 
-  \note this function expects the context to always be an struct ldb_result pointer
+  \note this function expects req->context to always be an struct ldb_result pointer
   AND a talloc context, this function will steal on the context each message
   from the ares reply passed on by the async core so that in the end all the
   messages will be in the context (ldb_result)  memory tree.
@@ -1117,7 +1162,9 @@ int ldb_delete(struct ldb_context *ldb, struct ldb_dn *dn);
   (the request need to be freed separately and the result doe not depend on the
   request that can be freed as sson as the search request is finished)
 */
-int ldb_extended_default_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares);
+
+int ldb_extended_default_callback(struct ldb_request *req, struct ldb_reply *ares);
+
 
 /**
   Helper function to build a extended request
@@ -1130,7 +1177,8 @@ int ldb_extended_default_callback(struct ldb_context *ldb, void *context, struct
   it needs to be NULL or a valid talloc pointer! talloc_get_type() will be used on it  
   \param controls an array of controls
   \param context the callback function context
-  \param callback the callback function to handle the async replies
+  \param the callback function to handle the async replies
+  \param the parent request if any
 
   \return result code (LDB_SUCCESS on success, or a failure code)
 */
@@ -1141,7 +1189,8 @@ int ldb_build_extended_req(struct ldb_request **ret_req,
                           void *data,/* NULL or a valid talloc pointer! talloc_get_type() will be used on it */
                           struct ldb_control **controls,
                           void *context,
-                          ldb_request_callback_t callback);
+                          ldb_request_callback_t callback,
+                          struct ldb_request *parent);
 
 /**
   call an extended operation
index 30adadcfdc9e4fa0a126a68117babe65c4298b00..a92549d9ce7846d5d5624cb53404a6dcb2f31c1a 100644 (file)
@@ -43,6 +43,12 @@ struct ldb_module_ops;
 
 struct ldb_backend_ops;
 
+struct ldb_handle {
+       int status;
+       enum ldb_state state;
+       struct ldb_context *ldb;
+};
+
 /* basic module structure */
 struct ldb_module {
        struct ldb_module *prev, *next;
@@ -51,9 +57,8 @@ struct ldb_module {
        const struct ldb_module_ops *ops;
 };
 
-/* 
-   these function pointers define the operations that a ldb module must perform
-   they correspond exactly to the ldb_*() interface 
+/*
+   these function pointers define the operations that a ldb module can intercept
 */
 struct ldb_module_ops {
        const char *name;
@@ -68,23 +73,10 @@ struct ldb_module_ops {
        int (*start_transaction)(struct ldb_module *);
        int (*end_transaction)(struct ldb_module *);
        int (*del_transaction)(struct ldb_module *);
-       int (*wait)(struct ldb_handle *, enum ldb_wait_type);
        int (*sequence_number)(struct ldb_module *, struct ldb_request *);
     void *private_data;
 };
 
-
-typedef int (*ldb_connect_fn) (struct ldb_context *ldb, const char *url, unsigned int flags, const char *options[],
-                              struct ldb_module **module);
-
-
-struct ldb_backend_ops {
-       const char *name;
-       ldb_connect_fn connect_fn;
-};
-
-const char *ldb_default_modules_dir(void);
-
 /*
   schema related information needed for matching rules
 */
@@ -146,27 +138,6 @@ int ldb_connect_backend(struct ldb_context *ldb, const char *url, const char *op
                        struct ldb_module **backend_module);
 void ldb_set_default_dns(struct ldb_context *ldb);
 
-/* The following definitions come from lib/ldb/common/ldb_modules.c  */
-
-const char **ldb_modules_list_from_string(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const char *string);
-int ldb_load_modules_list(struct ldb_context *ldb, const char **module_list, struct ldb_module *backend, struct ldb_module **out);
-int ldb_load_modules(struct ldb_context *ldb, const char *options[]);
-int ldb_init_module_chain(struct ldb_context *ldb, struct ldb_module *module);
-int ldb_next_request(struct ldb_module *module, struct ldb_request *request);
-int ldb_next_start_trans(struct ldb_module *module);
-int ldb_next_end_trans(struct ldb_module *module);
-int ldb_next_del_trans(struct ldb_module *module);
-int ldb_next_init(struct ldb_module *module);
-
-void ldb_set_errstring(struct ldb_context *ldb, const char *err_string);
-void ldb_asprintf_errstring(struct ldb_context *ldb, const char *format, ...) PRINTF_ATTRIBUTE(2,3);
-void ldb_reset_err_string(struct ldb_context *ldb);
-
-int ldb_register_module(const struct ldb_module_ops *);
-int ldb_register_backend(const char *url_prefix, ldb_connect_fn);
-void *ldb_dso_load_symbol(struct ldb_context *ldb, const char *name,
-                           const char *symbol);
-
 /* The following definitions come from lib/ldb/common/ldb_debug.c  */
 void ldb_debug(struct ldb_context *ldb, enum ldb_debug_level level, const char *fmt, ...) PRINTF_ATTRIBUTE(3, 4);
 void ldb_debug_set(struct ldb_context *ldb, enum ldb_debug_level level, 
@@ -249,4 +220,57 @@ int ldb_sequence_number(struct ldb_context *ldb, enum ldb_sequence_type type, ui
 #define LDB_SEQ_TIMESTAMP_SEQUENCE 0x02
 
 
+/* MODULES specific headers -- SSS */
+
+/* The following definitions come from lib/ldb/common/ldb_modules.c  */
+
+const char **ldb_modules_list_from_string(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const char *string);
+int ldb_load_modules_list(struct ldb_context *ldb, const char **module_list, struct ldb_module *backend, struct ldb_module **out);
+int ldb_load_modules(struct ldb_context *ldb, const char *options[]);
+int ldb_init_module_chain(struct ldb_context *ldb, struct ldb_module *module);
+int ldb_next_request(struct ldb_module *module, struct ldb_request *request);
+int ldb_next_start_trans(struct ldb_module *module);
+int ldb_next_end_trans(struct ldb_module *module);
+int ldb_next_del_trans(struct ldb_module *module);
+int ldb_next_init(struct ldb_module *module);
+
+void ldb_set_errstring(struct ldb_context *ldb, const char *err_string);
+void ldb_asprintf_errstring(struct ldb_context *ldb, const char *format, ...) PRINTF_ATTRIBUTE(2,3);
+void ldb_reset_err_string(struct ldb_context *ldb);
+
+const char *ldb_default_modules_dir(void);
+
+int ldb_register_module(const struct ldb_module_ops *);
+
+typedef int (*ldb_connect_fn)(struct ldb_context *ldb, const char *url,
+                             unsigned int flags, const char *options[],
+                             struct ldb_module **module);
+
+struct ldb_backend_ops {
+       const char *name;
+       ldb_connect_fn connect_fn;
+};
+
+const char *ldb_default_modules_dir(void);
+
+int ldb_register_backend(const char *url_prefix, ldb_connect_fn);
+
+void *ldb_dso_load_symbol(struct ldb_context *ldb, const char *name,
+                           const char *symbol);
+
+struct ldb_handle *ldb_handle_new(TALLOC_CTX *mem_ctx, struct ldb_context *ldb);
+
+int ldb_module_send_entry(struct ldb_request *req,
+                         struct ldb_message *msg);
+
+int ldb_module_send_referral(struct ldb_request *req,
+                                          char *ref);
+
+int ldb_module_done(struct ldb_request *req,
+                   struct ldb_control **ctrls,
+                   struct ldb_extended *response,
+                   int error);
+
+int ldb_mod_register_control(struct ldb_module *module, const char *oid);
+
 #endif
index 45978251f7506990f6004e0fcb3ffa2687d68158..024ba1959a0b09b63524596edb1c8cffd30598d7 100644 (file)
@@ -737,15 +737,14 @@ typedef struct ldb_context {
                            attrs,
                            controls,
                            res,
-                           ldb_search_default_callback);
+                           ldb_search_default_callback,
+                           NULL);
 
             if (ret != LDB_SUCCESS) {
                 talloc_free(res);
                 return ret;
             }
 
-            ldb_set_timeout($self, req, 0); /* use default timeout */
-                
             ret = ldb_request($self, req);
                 
             if (ret == LDB_SUCCESS) {
@@ -1220,22 +1219,6 @@ int py_module_del_transaction(struct ldb_module *mod)
     return LDB_SUCCESS;
 }
 
-int py_module_wait(struct ldb_handle *mod, enum ldb_wait_type wait_type)
-{
-    PyObject *py_ldb = mod->private_data;
-    PyObject *py_result;
-
-    py_result = PyObject_CallMethod(py_ldb, "wait", "i", wait_type);
-
-    if (py_result == NULL) {
-        return LDB_ERR_OPERATIONS_ERROR;
-    }
-
-    Py_DECREF(py_result);
-
-    return LDB_SUCCESS;
-}
-
 int py_module_sequence_number(struct ldb_module *mod, struct ldb_request *req)
 {
     PyObject *py_ldb = mod->private_data;
@@ -1309,7 +1292,6 @@ int py_module_init (struct ldb_module *mod)
     $1->start_transaction = py_module_start_transaction;
     $1->end_transaction = py_module_end_transaction;
     $1->del_transaction = py_module_del_transaction;
-    $1->wait = py_module_wait;
     $1->sequence_number = py_module_sequence_number;
 }
 
index 5ad671ea2ea16e505c1cfdf821cc79a8e76c4405..4aa71e603672b6a77a6f1632e3ad8b2bf85b6772 100644 (file)
 
 struct ildb_private {
        struct ldap_connection *ldap;
-       struct ldb_module *module;
+       struct event_context *event_ctx;
 };
 
 struct ildb_context {
+       struct ldb_module *module;
+       struct ldb_request *req;
+
        struct ildb_private *ildb;
-       struct ldb_handle *handle;
-       struct ldap_request *req;
-       void *context;
-       int (*callback)(struct ldb_context *, void *, struct ldb_reply *);
+       struct ldap_request *ireq;
+
+       bool done;
+
+       struct ildb_destructor_ctx *dc;
 };
 
+static void ildb_request_done(struct ildb_context *ctx,
+                             struct ldb_control **ctrls, int error)
+{
+       struct ldb_reply *ares;
+
+       ctx->done = true;
+
+       if (ctx->req == NULL) {
+               /* if the req has been freed already just return */
+               return;
+       }
+
+       ares = talloc_zero(ctx->req, struct ldb_reply);
+       if (!ares) {
+               ldb_oom(ctx->req->handle->ldb);
+               ctx->req->callback(ctx->req, NULL);
+               return;
+       }
+       ares->type = LDB_REPLY_DONE;
+       ares->controls = talloc_steal(ares, ctrls);
+       ares->error = error;
+
+       ctx->req->callback(ctx->req, ares);
+}
+
+static void ildb_auto_done_callback(struct event_context *ev,
+                                   struct timed_event *te,
+                                   struct timeval t,
+                                   void *private_data)
+{
+       struct ildb_context *ac;
+
+       ac = talloc_get_type(private_data, struct ildb_context);
+       ildb_request_done(ac, NULL, LDB_SUCCESS);
+}
+
 /*
   convert a ldb_message structure to a list of ldap_mod structures
   ready for ildap_add() or ildap_modify()
@@ -122,17 +162,19 @@ failed:
 /*
   map an ildap NTSTATUS to a ldb error code
 */
-static int ildb_map_error(struct ildb_private *ildb, NTSTATUS status)
+static int ildb_map_error(struct ldb_module *module, NTSTATUS status)
 {
+       struct ildb_private *ildb = talloc_get_type(module->private_data, struct ildb_private);
+
        TALLOC_CTX *mem_ctx = talloc_new(ildb);
        if (NT_STATUS_IS_OK(status)) {
                return LDB_SUCCESS;
        }
        if (!mem_ctx) {
-               ldb_oom(ildb->module->ldb);
+               ldb_oom(module->ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       ldb_set_errstring(ildb->module->ldb,
+       ldb_set_errstring(module->ldb,
                          ldap_errstr(ildb->ldap, mem_ctx, status));
        talloc_free(mem_ctx);
        if (NT_STATUS_IS_LDAP(status)) {
@@ -141,47 +183,46 @@ static int ildb_map_error(struct ildb_private *ildb, NTSTATUS status)
        return LDB_ERR_OPERATIONS_ERROR;
 }
 
-static void ildb_request_timeout(struct event_context *ev,
-                                struct timed_event *te,
+static void ildb_request_timeout(struct event_context *ev, struct timed_event *te,
                                 struct timeval t, void *private_data)
 {
-       struct ildb_context *ac;
-       struct ldb_handle *handle;
-
-       ac = talloc_get_type(private_data, struct ildb_context);
-       handle = ac->handle;
-
-       ac = talloc_get_type(private_data, struct ildb_context);
+       struct ildb_context *ac = talloc_get_type(private_data, struct ildb_context);
 
-       if (ac->req->state == LDAP_REQUEST_PENDING) {
-               DLIST_REMOVE(ac->req->conn->pending, ac->req);
+       if (ac->ireq->state == LDAP_REQUEST_PENDING) {
+               DLIST_REMOVE(ac->ireq->conn->pending, ac->ireq);
        }
 
-       handle->status = LDB_ERR_TIME_LIMIT_EXCEEDED;
-
-       return;
+       ildb_request_done(ac, NULL, LDB_ERR_TIME_LIMIT_EXCEEDED);
 }
 
 static void ildb_callback(struct ldap_request *req)
 {
        struct ildb_context *ac;
-       struct ldb_handle *handle;
-       struct ildb_private *ildb;
        NTSTATUS status;
+       struct ldap_SearchResEntry *search;
+       struct ldap_message *msg;
+       struct ldb_control **controls;
+       struct ldb_message *ldbmsg;
+       char *referral;
+       bool callback_failed;
+       bool request_done;
+       int ret;
        int i;
 
        ac = talloc_get_type(req->async.private_data, struct ildb_context);
-       ildb = ac->ildb;
-       handle = ac->handle;
-       handle->status = LDB_SUCCESS;
+       callback_failed = false;
+       request_done = false;
+       controls = NULL;
 
        if (!NT_STATUS_IS_OK(req->status)) {
-               handle->status = ildb_map_error(ildb, req->status);
+               ret = ildb_map_error(ac->module, req->status);
+               ildb_request_done(ac, NULL, ret);
                return;
        }
 
        if (req->num_replies < 1) {
-               handle->status = LDB_ERR_OPERATIONS_ERROR;
+               ret = LDB_ERR_OPERATIONS_ERROR;
+               ildb_request_done(ac, NULL, ret);
                return;
        }
 
@@ -189,140 +230,112 @@ static void ildb_callback(struct ldap_request *req)
 
        case LDAP_TAG_ModifyRequest:
                if (req->replies[0]->type != LDAP_TAG_ModifyResponse) {
-                       handle->status = LDB_ERR_PROTOCOL_ERROR;
-                       return;
+                       ret = LDB_ERR_PROTOCOL_ERROR;
+                       break;
                }
-               status = ldap_check_response(req->conn, &req->replies[0]->r.GeneralResult);
-               handle->status = ildb_map_error(ildb, status);
-               if (ac->callback && handle->status == LDB_SUCCESS) {
-                       /* FIXME: build a corresponding ares to pass on */
-                       handle->status = ac->callback(ac->ildb->module->ldb, ac->context, NULL);
-               }
-               handle->state = LDB_ASYNC_DONE;
+               status = ldap_check_response(ac->ireq->conn, &req->replies[0]->r.GeneralResult);
+               ret = ildb_map_error(ac->module, status);
+               request_done = true;
                break;
 
        case LDAP_TAG_AddRequest:
                if (req->replies[0]->type != LDAP_TAG_AddResponse) {
-                       handle->status = LDB_ERR_PROTOCOL_ERROR;
+                       ret = LDB_ERR_PROTOCOL_ERROR;
                        return;
                }
-               status = ldap_check_response(req->conn, &req->replies[0]->r.GeneralResult);
-               handle->status = ildb_map_error(ildb, status);
-               if (ac->callback && handle->status == LDB_SUCCESS) {
-                       /* FIXME: build a corresponding ares to pass on */
-                       handle->status = ac->callback(ac->ildb->module->ldb, ac->context, NULL);
-               }
-               handle->state = LDB_ASYNC_DONE;
+               status = ldap_check_response(ac->ireq->conn, &req->replies[0]->r.GeneralResult);
+               ret = ildb_map_error(ac->module, status);
+               request_done = true;
                break;
 
        case LDAP_TAG_DelRequest:
                if (req->replies[0]->type != LDAP_TAG_DelResponse) {
-                       handle->status = LDB_ERR_PROTOCOL_ERROR;
+                       ret = LDB_ERR_PROTOCOL_ERROR;
                        return;
                }
-               status = ldap_check_response(req->conn, &req->replies[0]->r.GeneralResult);
-               handle->status = ildb_map_error(ildb, status);
-               if (ac->callback && handle->status == LDB_SUCCESS) {
-                       /* FIXME: build a corresponding ares to pass on */
-                       handle->status = ac->callback(ac->ildb->module->ldb, ac->context, NULL);
-               }
-               handle->state = LDB_ASYNC_DONE;
+               status = ldap_check_response(ac->ireq->conn, &req->replies[0]->r.GeneralResult);
+               ret = ildb_map_error(ac->module, status);
+               request_done = true;
                break;
 
        case LDAP_TAG_ModifyDNRequest:
                if (req->replies[0]->type != LDAP_TAG_ModifyDNResponse) {
-                       handle->status = LDB_ERR_PROTOCOL_ERROR;
+                       ret = LDB_ERR_PROTOCOL_ERROR;
                        return;
                }
-               status = ldap_check_response(req->conn, &req->replies[0]->r.GeneralResult);
-               handle->status = ildb_map_error(ildb, status);
-               if (ac->callback && handle->status == LDB_SUCCESS) {
-                       /* FIXME: build a corresponding ares to pass on */
-                       handle->status = ac->callback(ac->ildb->module->ldb, ac->context, NULL);
-               }
-               handle->state = LDB_ASYNC_DONE;
+               status = ldap_check_response(ac->ireq->conn, &req->replies[0]->r.GeneralResult);
+               ret = ildb_map_error(ac->module, status);
+               request_done = true;
                break;
 
        case LDAP_TAG_SearchRequest:
                /* loop over all messages */
                for (i = 0; i < req->num_replies; i++) {
-                       struct ldap_SearchResEntry *search;
-                       struct ldb_reply *ares = NULL;
-                       struct ldap_message *msg;
-                       int ret;
-
-                       ares = talloc_zero(ac, struct ldb_reply);
-                       if (!ares) {
-                               handle->status = LDB_ERR_OPERATIONS_ERROR;
-                               return;
-                       }
 
                        msg = req->replies[i];
                        switch (msg->type) {
 
                        case LDAP_TAG_SearchResultDone:
 
-                               status = ldap_check_response(req->conn, &msg->r.GeneralResult);
+                               status = ldap_check_response(ac->ireq->conn, &msg->r.GeneralResult);
                                if (!NT_STATUS_IS_OK(status)) {
-                                       handle->status = ildb_map_error(ildb, status);
-                                       return;
+                                       ret = ildb_map_error(ac->module, status);
+                                       break;
                                }
 
-                               ares->controls = talloc_move(ares, &msg->controls);
+                               controls = talloc_steal(ac, msg->controls);
                                if (msg->r.SearchResultDone.resultcode) {
                                        if (msg->r.SearchResultDone.errormessage) {
-                                               ldb_set_errstring(ac->ildb->module->ldb, msg->r.SearchResultDone.errormessage);
+                                               ldb_set_errstring(ac->module->ldb, msg->r.SearchResultDone.errormessage);
                                        }
                                }
 
-                               handle->status = msg->r.SearchResultDone.resultcode;
-                               handle->state = LDB_ASYNC_DONE;
-                               ares->type = LDB_REPLY_DONE;
+                               ret = msg->r.SearchResultDone.resultcode;
+                               request_done = true;
                                break;
 
                        case LDAP_TAG_SearchResultEntry:
 
-
-                               ares->message = ldb_msg_new(ares);
-                               if (!ares->message) {
-                                       handle->status = LDB_ERR_OPERATIONS_ERROR;
-                                       return;
+                               ldbmsg = ldb_msg_new(ac);
+                               if (!ldbmsg) {
+                                       ret = LDB_ERR_OPERATIONS_ERROR;
+                                       break;
                                }
 
                                search = &(msg->r.SearchResultEntry);
 
-                               ares->message->dn = ldb_dn_new(ares->message, ac->ildb->module->ldb, search->dn);
-                               if ( ! ldb_dn_validate(ares->message->dn)) {
-                                       handle->status = LDB_ERR_OPERATIONS_ERROR;
-                                       return;
+                               ldbmsg->dn = ldb_dn_new(ldbmsg, ac->module->ldb, search->dn);
+                               if ( ! ldb_dn_validate(ldbmsg->dn)) {
+                                       ret = LDB_ERR_OPERATIONS_ERROR;
+                                       break;
                                }
-                               ares->message->num_elements = search->num_attributes;
-                               ares->message->elements = talloc_move(ares->message,
-                                                                     &search->attributes);
+                               ldbmsg->num_elements = search->num_attributes;
+                               ldbmsg->elements = talloc_move(ldbmsg, &search->attributes);
 
-                               handle->status = LDB_SUCCESS;
-                               handle->state = LDB_ASYNC_PENDING;
-                               ares->type = LDB_REPLY_ENTRY;
+                               ret = ldb_module_send_entry(ac->req, ldbmsg);
+                               if (ret != LDB_SUCCESS) {
+                                       callback_failed = true;
+                               }
                                break;
 
                        case LDAP_TAG_SearchResultReference:
 
-                               ares->referral = talloc_strdup(ares, msg->r.SearchResultReference.referral);
+                               referral = talloc_strdup(ac, msg->r.SearchResultReference.referral);
 
-                               handle->status = LDB_SUCCESS;
-                               handle->state = LDB_ASYNC_PENDING;
-                               ares->type = LDB_REPLY_REFERRAL;
+                               ret = ldb_module_send_referral(ac->req, referral);
+                               if (ret != LDB_SUCCESS) {
+                                       callback_failed = true;
+                               }
                                break;
 
                        default:
                                /* TAG not handled, fail ! */
-                               handle->status = LDB_ERR_PROTOCOL_ERROR;
-                               return;
+                               ret = LDB_ERR_PROTOCOL_ERROR;
+                               break;
                        }
 
-                       ret = ac->callback(ac->ildb->module->ldb, ac->context, ares);
-                       if (ret) {
-                               handle->status = ret;
+                       if (ret != LDB_SUCCESS) {
+                               break;
                        }
                }
 
@@ -333,121 +346,81 @@ static void ildb_callback(struct ldap_request *req)
                break;
 
        default:
-               handle->status = LDB_ERR_PROTOCOL_ERROR;
-               return;
+               ret = LDB_ERR_PROTOCOL_ERROR;
+               break;
        }
-}
 
-static struct ildb_context *init_ildb_handle(struct ildb_private *ildb,
-                                            struct ldb_request *req)
-{
-       struct ildb_context *ildb_ac;
-       struct ldb_handle *h;
+       if (ret != LDB_SUCCESS) {
 
-       h = talloc_zero(req, struct ldb_handle);
-       if (h == NULL) {
-               ldb_set_errstring(ildb->module->ldb, "Out of Memory");
-               return NULL;
+               /* if the callback failed the caller will have freed the
+                * request. Just return and don't try to use it */
+               if ( ! callback_failed) {
+                       request_done = true;
+               }
        }
 
-       h->module = ildb->module;
-
-       ildb_ac = talloc(h, struct ildb_context);
-       if (ildb_ac == NULL) {
-               ldb_set_errstring(ildb->module->ldb, "Out of Memory");
-               talloc_free(h);
-               return NULL;
+       if (request_done) {
+               ildb_request_done(ac, controls, ret);
        }
-
-       h->private_data = ildb_ac;
-
-       h->state = LDB_ASYNC_INIT;
-       h->status = LDB_SUCCESS;
-
-       ildb_ac->ildb = ildb;
-       ildb_ac->handle = h;
-       ildb_ac->context = req->context;
-       ildb_ac->callback = req->callback;
-
-       req->handle = h;
-       return ildb_ac;
+       return;
 }
 
-static int ildb_request_send(struct ildb_private *ildb, struct ldap_message *msg, struct ldb_request *r)
+static int ildb_request_send(struct ildb_context *ac, struct ldap_message *msg)
 {
-       struct ildb_context *ildb_ac = init_ildb_handle(ildb, r);
        struct ldap_request *req;
 
-       if (!ildb_ac) {
+       if (!ac) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       req = ldap_request_send(ildb->ldap, msg);
+       req = ldap_request_send(ac->ildb->ldap, msg);
        if (req == NULL) {
-               ldb_set_errstring(ildb->module->ldb, "async send request failed");
+               ldb_set_errstring(ac->module->ldb, "async send request failed");
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       ildb_ac->req = talloc_steal(ildb_ac, req);
+       ac->ireq = talloc_steal(ac, req);
 
-       if (!req->conn) {
-               ldb_set_errstring(ildb->module->ldb, "connection to remote LDAP server dropped?");
+       if (!ac->ireq->conn) {
+               ldb_set_errstring(ac->module->ldb, "connection to remote LDAP server dropped?");
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
        talloc_free(req->time_event);
        req->time_event = NULL;
-       if (r->timeout) {
-               req->time_event = event_add_timed(req->conn->event.event_ctx, ildb_ac, 
-                                                 timeval_current_ofs(r->timeout, 0),
-                                                 ildb_request_timeout, ildb_ac);
+       if (ac->req->timeout) {
+               req->time_event = event_add_timed(ac->ildb->event_ctx, ac,
+                                                 timeval_current_ofs(ac->req->timeout, 0),
+                                                 ildb_request_timeout, ac);
        }
 
        req->async.fn = ildb_callback;
-       req->async.private_data = ildb_ac;
+       req->async.private_data = ac;
 
        return LDB_SUCCESS;
 }
 
-static int ildb_request_noop(struct ildb_private *ildb, struct ldb_request *req) 
-{
-       struct ildb_context *ildb_ac = init_ildb_handle(ildb, req);
-       int ret = LDB_SUCCESS;
-
-       if (!ildb_ac) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       if (ildb_ac->callback) {
-               ret = ildb_ac->callback(ildb->module->ldb, ildb_ac->context, NULL);
-       }
-       ildb_ac->handle->state = LDB_ASYNC_DONE;
-       return ret;
-}
-
 /*
   search for matching records using an asynchronous function
  */
-static int ildb_search(struct ldb_module *module, struct ldb_request *req)
+static int ildb_search(struct ildb_context *ac)
 {
-       struct ildb_private *ildb = talloc_get_type(module->private_data, struct ildb_private);
+       struct ldb_request *req = ac->req;
        struct ldap_message *msg;
        int n;
 
-       req->handle = NULL;
-
        if (!req->callback || !req->context) {
-               ldb_set_errstring(module->ldb, "Async interface called with NULL callback function or NULL context");
+               ldb_set_errstring(ac->module->ldb, "Async interface called with NULL callback function or NULL context");
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
        if (req->op.search.tree == NULL) {
-               ldb_set_errstring(module->ldb, "Invalid expression parse tree");
+               ldb_set_errstring(ac->module->ldb, "Invalid expression parse tree");
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
        msg = new_ldap_message(req);
        if (msg == NULL) {
-               ldb_set_errstring(module->ldb, "Out of Memory");
+               ldb_set_errstring(ac->module->ldb, "Out of Memory");
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
@@ -459,7 +432,7 @@ static int ildb_search(struct ldb_module *module, struct ldb_request *req)
                msg->r.SearchRequest.basedn  = ldb_dn_alloc_linearized(msg, req->op.search.base);
        }
        if (msg->r.SearchRequest.basedn == NULL) {
-               ldb_set_errstring(module->ldb, "Unable to determine baseDN");
+               ldb_set_errstring(ac->module->ldb, "Unable to determine baseDN");
                talloc_free(msg);
                return LDB_ERR_OPERATIONS_ERROR;
        }
@@ -481,26 +454,19 @@ static int ildb_search(struct ldb_module *module, struct ldb_request *req)
        msg->r.SearchRequest.attributes = discard_const(req->op.search.attrs);
        msg->controls = req->controls;
 
-       return ildb_request_send(ildb, msg, req);
+       return ildb_request_send(ac, msg);
 }
 
 /*
   add a record
 */
-static int ildb_add(struct ldb_module *module, struct ldb_request *req)
+static int ildb_add(struct ildb_context *ac)
 {
-       struct ildb_private *ildb = talloc_get_type(module->private_data, struct ildb_private);
+       struct ldb_request *req = ac->req;
        struct ldap_message *msg;
        struct ldap_mod **mods;
        int i,n;
 
-       req->handle = NULL;
-
-       /* ignore ltdb specials */
-       if (ldb_dn_is_special(req->op.add.message->dn)) {
-               return ildb_request_noop(ildb, req);
-       }
-
        msg = new_ldap_message(req);
        if (msg == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
@@ -531,26 +497,19 @@ static int ildb_add(struct ldb_module *module, struct ldb_request *req)
                msg->r.AddRequest.attributes[i] = mods[i]->attrib;
        }
 
-       return ildb_request_send(ildb, msg, req);
+       return ildb_request_send(ac, msg);
 }
 
 /*
   modify a record
 */
-static int ildb_modify(struct ldb_module *module, struct ldb_request *req)
+static int ildb_modify(struct ildb_context *ac)
 {
-       struct ildb_private *ildb = talloc_get_type(module->private_data, struct ildb_private);
+       struct ldb_request *req = ac->req;
        struct ldap_message *msg;
        struct ldap_mod **mods;
        int i,n;
 
-       req->handle = NULL;
-
-       /* ignore ltdb specials */
-       if (ldb_dn_is_special(req->op.mod.message->dn)) {
-               return ildb_request_noop(ildb, req);
-       }
-
        msg = new_ldap_message(req);
        if (msg == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
@@ -581,24 +540,17 @@ static int ildb_modify(struct ldb_module *module, struct ldb_request *req)
                msg->r.ModifyRequest.mods[i] = *mods[i];
        }
 
-       return ildb_request_send(ildb, msg, req);
+       return ildb_request_send(ac, msg);
 }
 
 /*
   delete a record
 */
-static int ildb_delete(struct ldb_module *module, struct ldb_request *req)
+static int ildb_delete(struct ildb_context *ac)
 {
-       struct ildb_private *ildb = talloc_get_type(module->private_data, struct ildb_private);
+       struct ldb_request *req = ac->req;
        struct ldap_message *msg;
 
-       req->handle = NULL;
-
-       /* ignore ltdb specials */
-       if (ldb_dn_is_special(req->op.del.dn)) {
-               return ildb_request_noop(ildb, req);
-       }
-
        msg = new_ldap_message(req);
        if (msg == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
@@ -612,24 +564,17 @@ static int ildb_delete(struct ldb_module *module, struct ldb_request *req)
                return LDB_ERR_INVALID_DN_SYNTAX;
        }
 
-       return ildb_request_send(ildb, msg, req);
+       return ildb_request_send(ac, msg);
 }
 
 /*
   rename a record
 */
-static int ildb_rename(struct ldb_module *module, struct ldb_request *req)
+static int ildb_rename(struct ildb_context *ac)
 {
-       struct ildb_private *ildb = talloc_get_type(module->private_data, struct ildb_private);
+       struct ldb_request *req = ac->req;
        struct ldap_message *msg;
 
-       req->handle = NULL;
-
-       /* ignore ltdb specials */
-       if (ldb_dn_is_special(req->op.rename.olddn) || ldb_dn_is_special(req->op.rename.newdn)) {
-               return ildb_request_noop(ildb, req);
-       }
-
        msg = new_ldap_message(req);
        if (msg == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
@@ -660,7 +605,7 @@ static int ildb_rename(struct ldb_module *module, struct ldb_request *req)
 
        msg->r.ModifyDNRequest.deleteolddn = true;
 
-       return ildb_request_send(ildb, msg, req);
+       return ildb_request_send(ac, msg);
 }
 
 static int ildb_start_trans(struct ldb_module *module)
@@ -684,57 +629,105 @@ static int ildb_del_trans(struct ldb_module *module)
        return LDB_SUCCESS;
 }
 
-static int ildb_request(struct ldb_module *module, struct ldb_request *req)
+static bool ildb_dn_is_special(struct ldb_request *req)
 {
-       return LDB_ERR_OPERATIONS_ERROR;
+       struct ldb_dn *dn = NULL;
+
+       switch (req->operation) {
+       case LDB_ADD:
+               dn = req->op.add.message->dn;
+               break;
+       case LDB_MODIFY:
+               dn = req->op.mod.message->dn;
+               break;
+       case LDB_DELETE:
+               dn = req->op.del.dn;
+               break;
+       case LDB_RENAME:
+               dn = req->op.rename.olddn;
+               break;
+       default:
+               break;
+       }
+
+       if (dn && ldb_dn_is_special(dn)) {
+               return true;
+       }
+       return false;
 }
 
-static int ildb_wait(struct ldb_handle *handle, enum ldb_wait_type type)
+static int ildb_handle_request(struct ldb_module *module, struct ldb_request *req)
 {
-       struct ildb_context *ac = talloc_get_type(handle->private_data, struct ildb_context);
+       struct ildb_private *ildb;
+       struct ildb_context *ac;
+       struct timed_event *te;
+       int ret;
+
+       ildb = talloc_get_type(module->private_data, struct ildb_private);
 
-       if (handle->state == LDB_ASYNC_DONE) {
-               return handle->status;
+       if (req->starttime == 0 || req->timeout == 0) {
+               ldb_set_errstring(module->ldb, "Invalid timeout settings");
+               return LDB_ERR_TIME_LIMIT_EXCEEDED;
        }
 
-       if (!ac) {
+       ac = talloc_zero(req, struct ildb_context);
+       if (ac == NULL) {
+               ldb_set_errstring(module->ldb, "Out of Memory");
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       handle->state = LDB_ASYNC_INIT;
+       ac->module = module;
+       ac->req = req;
+       ac->ildb = ildb;
+
+       if (ildb_dn_is_special(req)) {
 
-       switch(type) {
-       case LDB_WAIT_NONE:
-               if (event_loop_once(ac->req->conn->event.event_ctx) != 0) {
-                       return LDB_ERR_OTHER;
+               te = event_add_timed(ac->ildb->event_ctx,
+                                       ac, timeval_zero(),
+                                       ildb_auto_done_callback, ac);
+               if (NULL == te) {
+                       return LDB_ERR_OPERATIONS_ERROR;
                }
+
+               return LDB_SUCCESS;
+       }
+
+       switch (ac->req->operation) {
+       case LDB_SEARCH:
+               ret = ildb_search(ac);
                break;
-       case LDB_WAIT_ALL:
-               while (handle->status == LDB_SUCCESS && handle->state != LDB_ASYNC_DONE) {
-                       if (event_loop_once(ac->req->conn->event.event_ctx) != 0) {
-                               return LDB_ERR_OTHER;
-                       }
-               }
+       case LDB_ADD:
+               ret = ildb_add(ac);
+               break;
+       case LDB_MODIFY:
+               ret = ildb_modify(ac);
+               break;
+       case LDB_DELETE:
+               ret = ildb_delete(ac);
+               break;
+       case LDB_RENAME:
+               ret = ildb_rename(ac);
                break;
        default:
-               return LDB_ERR_OPERATIONS_ERROR;
+               /* no other op supported */
+               ret = LDB_ERR_OPERATIONS_ERROR;
+               break;
        }
 
-       return handle->status;
+       return ret;
 }
 
 static const struct ldb_module_ops ildb_ops = {
        .name              = "ldap",
-       .search            = ildb_search,
-       .add               = ildb_add,
-       .modify            = ildb_modify,
-       .del               = ildb_delete,
-       .rename            = ildb_rename,
-       .request           = ildb_request,
+       .search            = ildb_handle_request,
+       .add               = ildb_handle_request,
+       .modify            = ildb_handle_request,
+       .del               = ildb_handle_request,
+       .rename            = ildb_handle_request,
+/*     .request           = ildb_handle_request, */
        .start_transaction = ildb_start_trans,
        .end_transaction   = ildb_end_trans,
        .del_transaction   = ildb_del_trans,
-       .wait              = ildb_wait
 };
 
 /*
@@ -748,7 +741,6 @@ static int ildb_connect(struct ldb_context *ldb, const char *url,
        struct ildb_private *ildb;
        NTSTATUS status;
        struct cli_credentials *creds;
-       struct event_context *event_ctx;
 
        module = talloc(ldb, struct ldb_module);
        if (!module) {
@@ -758,7 +750,6 @@ static int ildb_connect(struct ldb_context *ldb, const char *url,
        talloc_set_name_const(module, "ldb_ildap backend");
        module->ldb             = ldb;
        module->prev            = module->next = NULL;
-       module->private_data    = NULL;
        module->ops             = &ildb_ops;
 
        ildb = talloc(module, struct ildb_private);
@@ -767,12 +758,12 @@ static int ildb_connect(struct ldb_context *ldb, const char *url,
                goto failed;
        }
        module->private_data    = ildb;
-       ildb->module            = module;
 
-       event_ctx = ldb_get_event_context(ldb);
+       ildb->event_ctx = ldb_get_event_context(ldb);
+
 
        ildb->ldap = ldap4_new_connection(ildb, ldb_get_opaque(ldb, "loadparm"),
-                                         event_ctx);
+                                         ildb->event_ctx);
        if (!ildb->ldap) {
                ldb_oom(ldb);
                goto failed;
index a4534c549ad93a7fd9d70245c521dde7af1ce4bd..7caee10b47f3ed431849dd2e893edb964ff3c03c 100644 (file)
 
 struct lldb_private {
        LDAP *ldap;
-       struct ldb_module *module;
 };
 
 struct lldb_context {
+       struct ldb_module *module;
+       struct ldb_request *req;
+
        struct lldb_private *lldb;
-       struct ldb_handle *handle;
+
+       struct ldb_control **controls;
        int msgid;
-       int timeout;
-       time_t starttime;
-       void *context;
-       int (*callback)(struct ldb_context *, void *, struct ldb_reply *);
 };
 
 static int lldb_ldap_to_ldb(int err) {
@@ -63,42 +62,6 @@ static int lldb_ldap_to_ldb(int err) {
        return err;
 }
 
-static struct lldb_context *init_lldb_handle(struct lldb_private *lldb, struct ldb_request *req)
-{
-       struct lldb_context *ac;
-       struct ldb_handle *h;
-
-       h = talloc_zero(req, struct ldb_handle);
-       if (h == NULL) {
-               ldb_set_errstring(lldb->module->ldb, "Out of Memory");
-               return NULL;
-       }
-
-       h->module = lldb->module;
-
-       ac = talloc(h, struct lldb_context);
-       if (ac == NULL) {
-               ldb_set_errstring(lldb->module->ldb, "Out of Memory");
-               talloc_free(h);
-               return NULL;
-       }
-
-       h->private_data = ac;
-
-       h->state = LDB_ASYNC_INIT;
-       h->status = LDB_SUCCESS;
-
-       ac->lldb = lldb;
-       ac->handle = h;
-       ac->context = req->context;
-       ac->callback = req->callback;
-       ac->timeout = req->timeout;
-       ac->starttime = req->starttime;
-       ac->msgid = 0;
-
-       req->handle = h;
-       return ac;
-}
 /*
   convert a ldb_message structure to a list of LDAPMod structures
   ready for ldap_add() or ldap_modify()
@@ -230,10 +193,11 @@ static int lldb_add_msg_attr(struct ldb_context *ldb,
 /*
   search for matching records
 */
-static int lldb_search(struct ldb_module *module, struct ldb_request *req)
+static int lldb_search(struct lldb_context *lldb_ac)
 {
-       struct lldb_private *lldb = talloc_get_type(module->private_data, struct lldb_private);
-       struct lldb_context *lldb_ac;
+       struct lldb_private *lldb = lldb_ac->lldb;
+       struct ldb_module *module = lldb_ac->module;
+       struct ldb_request *req = lldb_ac->req;
        struct timeval tv;
        int ldap_scope;
        char *search_base;
@@ -254,10 +218,7 @@ static int lldb_search(struct ldb_module *module, struct ldb_request *req)
                ldb_debug(module->ldb, LDB_DEBUG_WARNING, "Controls are not yet supported by ldb_ldap backend!\n");
        }
 
-       lldb_ac = init_lldb_handle(lldb, req);
-       if (lldb_ac == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
+       req->handle->state = LDB_ASYNC_PENDING;
 
        search_base = ldb_dn_alloc_linearized(lldb_ac, req->op.search.base);
        if (req->op.search.base == NULL) {
@@ -307,23 +268,16 @@ static int lldb_search(struct ldb_module *module, struct ldb_request *req)
 /*
   add a record
 */
-static int lldb_add(struct ldb_module *module, struct ldb_request *req)
+static int lldb_add(struct lldb_context *lldb_ac)
 {
-       struct lldb_private *lldb = talloc_get_type(module->private_data, struct lldb_private);
-       struct lldb_context *lldb_ac;
+       struct lldb_private *lldb = lldb_ac->lldb;
+       struct ldb_module *module = lldb_ac->module;
+       struct ldb_request *req = lldb_ac->req;
        LDAPMod **mods;
        char *dn;
        int ret;
 
-       /* ltdb specials should not reach this point */
-       if (ldb_dn_is_special(req->op.add.message->dn)) {
-               return LDB_ERR_INVALID_DN_SYNTAX;
-       }
-
-       lldb_ac = init_lldb_handle(lldb, req);
-       if (lldb_ac == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
+       req->handle->state = LDB_ASYNC_PENDING;
 
        mods = lldb_msg_to_mods(lldb_ac, req->op.add.message, 0);
        if (mods == NULL) {
@@ -350,23 +304,16 @@ static int lldb_add(struct ldb_module *module, struct ldb_request *req)
 /*
   modify a record
 */
-static int lldb_modify(struct ldb_module *module, struct ldb_request *req)
+static int lldb_modify(struct lldb_context *lldb_ac)
 {
-       struct lldb_private *lldb = talloc_get_type(module->private_data, struct lldb_private);
-       struct lldb_context *lldb_ac;
+       struct lldb_private *lldb = lldb_ac->lldb;
+       struct ldb_module *module = lldb_ac->module;
+       struct ldb_request *req = lldb_ac->req;
        LDAPMod **mods;
        char *dn;
        int ret;
 
-       /* ltdb specials should not reach this point */
-       if (ldb_dn_is_special(req->op.mod.message->dn)) {
-               return LDB_ERR_INVALID_DN_SYNTAX;
-       }
-
-       lldb_ac = init_lldb_handle(lldb, req);
-       if (req->handle == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
+       req->handle->state = LDB_ASYNC_PENDING;
 
        mods = lldb_msg_to_mods(lldb_ac, req->op.mod.message, 1);
        if (mods == NULL) {
@@ -393,22 +340,15 @@ static int lldb_modify(struct ldb_module *module, struct ldb_request *req)
 /*
   delete a record
 */
-static int lldb_delete(struct ldb_module *module, struct ldb_request *req)
+static int lldb_delete(struct lldb_context *lldb_ac)
 {
-       struct lldb_private *lldb = talloc_get_type(module->private_data, struct lldb_private);
-       struct lldb_context *lldb_ac;
+       struct lldb_private *lldb = lldb_ac->lldb;
+       struct ldb_module *module = lldb_ac->module;
+       struct ldb_request *req = lldb_ac->req;
        char *dnstr;
        int ret;
-       
-       /* ltdb specials should not reach this point */
-       if (ldb_dn_is_special(req->op.del.dn)) {
-               return LDB_ERR_INVALID_DN_SYNTAX;
-       }
 
-       lldb_ac = init_lldb_handle(lldb, req);
-       if (lldb_ac == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
+       req->handle->state = LDB_ASYNC_PENDING;
 
        dnstr = ldb_dn_alloc_linearized(lldb_ac, req->op.del.dn);
 
@@ -427,24 +367,17 @@ static int lldb_delete(struct ldb_module *module, struct ldb_request *req)
 /*
   rename a record
 */
-static int lldb_rename(struct ldb_module *module, struct ldb_request *req)
+static int lldb_rename(struct lldb_context *lldb_ac)
 {
-       struct lldb_private *lldb = talloc_get_type(module->private_data, struct lldb_private);
-       struct lldb_context *lldb_ac;
+       struct lldb_private *lldb = lldb_ac->lldb;
+       struct ldb_module *module = lldb_ac->module;
+       struct ldb_request *req = lldb_ac->req;
        char *old_dn;
                char *newrdn;
        char *parentdn;
        int ret;
-       
-       /* ltdb specials should not reach this point */
-       if (ldb_dn_is_special(req->op.rename.olddn) || ldb_dn_is_special(req->op.rename.newdn)) {
-               return LDB_ERR_INVALID_DN_SYNTAX;
-       }
 
-       lldb_ac = init_lldb_handle(lldb, req);
-       if (lldb_ac == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
+       req->handle->state = LDB_ASYNC_PENDING;
 
        old_dn = ldb_dn_alloc_linearized(lldb_ac, req->op.rename.olddn);
        if (old_dn == NULL) {
@@ -474,57 +407,99 @@ static int lldb_rename(struct ldb_module *module, struct ldb_request *req)
        return lldb_ldap_to_ldb(ret);
 }
 
-static int lldb_parse_result(struct lldb_context *ac, LDAPMessage *result)
+static int lldb_start_trans(struct ldb_module *module)
+{
+       /* TODO implement a local transaction mechanism here */
+
+       return LDB_SUCCESS;
+}
+
+static int lldb_end_trans(struct ldb_module *module)
+{
+       /* TODO implement a local transaction mechanism here */
+
+       return LDB_SUCCESS;
+}
+
+static int lldb_del_trans(struct ldb_module *module)
+{
+       /* TODO implement a local transaction mechanism here */
+
+       return LDB_SUCCESS;
+}
+
+void lldb_request_done(struct ldb_request *req,
+                       struct ldb_control **ctrls, int error)
+{
+       struct ldb_reply *ares;
+
+       ares = talloc_zero(req, struct ldb_reply);
+       if (!ares) {
+               ldb_oom(req->handle->ldb);
+               req->callback(req, NULL);
+               return;
+       }
+       ares->type = LDB_REPLY_DONE;
+       ares->controls = talloc_steal(ares, ctrls);
+       ares->error = error;
+
+       req->callback(req, ares);
+}
+
+/* return false if the request is still in progress
+ * return true if the request is completed
+ */
+static bool lldb_parse_result(struct lldb_context *ac, LDAPMessage *result)
 {
-       struct ldb_handle *handle = ac->handle;
        struct lldb_private *lldb = ac->lldb;
-       struct ldb_reply *ares = NULL;
-       LDAPMessage *msg;
-       int type;
+       LDAPControl **serverctrlsp = NULL;
+       char **referralsp = NULL;
        char *matcheddnp = NULL;
        char *errmsgp = NULL;
-       char **referralsp = NULL;
-       LDAPControl **serverctrlsp = NULL;
-       int ret = LDB_SUCCESS;
-       
-       type = ldap_msgtype(result);
+       LDAPMessage *msg;
+       int type;
+       struct ldb_message *ldbmsg;
+       char *referral;
+       bool callback_failed;
+       bool request_done;
+       bool lret;
+       int ret;
+       int i;
 
-       handle->status = 0;
+       type = ldap_msgtype(result);
+       callback_failed = false;
+       request_done = false;
 
        switch (type) {
-
        case LDAP_RES_SEARCH_ENTRY:
+
                msg = ldap_first_entry(lldb->ldap, result);
                if (msg != NULL) {
                        BerElement *berptr = NULL;
                        char *attr, *dn;
 
-                       ares = talloc_zero(ac, struct ldb_reply);
-                       if (!ares) {
-                               ret = LDB_ERR_OPERATIONS_ERROR;
-                               goto error;
-                       }
-
-                       ares->message = ldb_msg_new(ares);
-                       if (!ares->message) {
+                       ldbmsg = ldb_msg_new(ac);
+                       if (!ldbmsg) {
                                ret = LDB_ERR_OPERATIONS_ERROR;
-                               goto error;
+                               break;
                        }
 
                        dn = ldap_get_dn(lldb->ldap, msg);
                        if (!dn) {
+                               talloc_free(ldbmsg);
                                ret = LDB_ERR_OPERATIONS_ERROR;
-                               goto error;
+                               break;
                        }
-                       ares->message->dn = ldb_dn_new(ares->message, ac->lldb->module->ldb, dn);
-                       if ( ! ldb_dn_validate(ares->message->dn)) {
+                       ldbmsg->dn = ldb_dn_new(ldbmsg, ac->module->ldb, dn);
+                       if ( ! ldb_dn_validate(ldbmsg->dn)) {
+                               talloc_free(ldbmsg);
                                ret = LDB_ERR_OPERATIONS_ERROR;
-                               goto error;
+                               break;
                        }
                        ldap_memfree(dn);
 
-                       ares->message->num_elements = 0;
-                       ares->message->elements = NULL;
+                       ldbmsg->num_elements = 0;
+                       ldbmsg->elements = NULL;
 
                        /* loop over all attributes */
                        for (attr=ldap_first_attribute(lldb->ldap, msg, &berptr);
@@ -534,97 +509,104 @@ static int lldb_parse_result(struct lldb_context *ac, LDAPMessage *result)
                                bval = ldap_get_values_len(lldb->ldap, msg, attr);
 
                                if (bval) {
-                                       lldb_add_msg_attr(ac->lldb->module->ldb, ares->message, attr, bval);
+                                       lldb_add_msg_attr(ac->module->ldb, ldbmsg, attr, bval);
                                        ldap_value_free_len(bval);
-                               }                                         
+                               }
                        }
                        if (berptr) ber_free(berptr, 0);
 
+                       ret = ldb_module_send_entry(ac->req, ldbmsg);
+                       if (ret != LDB_SUCCESS) {
 
-                       ares->type = LDB_REPLY_ENTRY;
-                       ret = ac->callback(ac->lldb->module->ldb, ac->context, ares);
+                               callback_failed = true;
+                       }
                } else {
-                       handle->status = LDB_ERR_PROTOCOL_ERROR;
-                       handle->state = LDB_ASYNC_DONE;
+                       ret = LDB_ERR_OPERATIONS_ERROR;
                }
                break;
 
        case LDAP_RES_SEARCH_REFERENCE:
-               if (ldap_parse_result(lldb->ldap, result, &handle->status,
+
+               if (ldap_parse_result(lldb->ldap, result, &ret,
                                        &matcheddnp, &errmsgp,
                                        &referralsp, &serverctrlsp, 0) != LDAP_SUCCESS) {
                        ret = LDB_ERR_OPERATIONS_ERROR;
-                       goto error;
                }
-               if (referralsp == NULL) {
-                       handle->status = LDB_ERR_PROTOCOL_ERROR;
-                       goto error;
+               if (ret != LDB_SUCCESS) {
+                       break;
                }
-
-               ares = talloc_zero(ac, struct ldb_reply);
-               if (!ares) {
-                       ret = LDB_ERR_OPERATIONS_ERROR;
-                       goto error;
+               if (referralsp == NULL) {
+                       ret = LDB_ERR_PROTOCOL_ERROR;
+                       break;
                }
 
-               ares->referral = talloc_strdup(ares, *referralsp);
-               ares->type = LDB_REPLY_REFERRAL;
-               ret = ac->callback(ac->lldb->module->ldb, ac->context, ares);
+               for (i = 0; referralsp[i]; i++) {
+                       referral = talloc_strdup(ac, referralsp[i]);
 
+                       ret = ldb_module_send_referral(ac->req, referral);
+                       if (ret != LDB_SUCCESS) {
+                               callback_failed = true;
+                               break;
+                       }
+               }
                break;
 
        case LDAP_RES_SEARCH_RESULT:
-               if (ldap_parse_result(lldb->ldap, result, &handle->status,
+       case LDAP_RES_MODIFY:
+       case LDAP_RES_ADD:
+       case LDAP_RES_DELETE:
+       case LDAP_RES_MODDN:
+
+               if (ldap_parse_result(lldb->ldap, result, &ret,
                                        &matcheddnp, &errmsgp,
                                        &referralsp, &serverctrlsp, 0) != LDAP_SUCCESS) {
-                       handle->status = LDB_ERR_OPERATIONS_ERROR;
-                       goto error;
-               }
-
-               ares = talloc_zero(ac, struct ldb_reply);
-               if (!ares) {
                        ret = LDB_ERR_OPERATIONS_ERROR;
-                       goto error;
+               }
+               if (ret != LDB_SUCCESS) {
+                       break;
                }
 
                if (serverctrlsp != NULL) {
                        /* FIXME: transform the LDAPControl list into an ldb_control one */
-                       ares->controls = NULL;
+                       ac->controls = NULL;
                }
-               
-               ares->type = LDB_REPLY_DONE;
-               handle->state = LDB_ASYNC_DONE;
-               ret = ac->callback(ac->lldb->module->ldb, ac->context, ares);
-
-               break;
 
-       case LDAP_RES_MODIFY:
-       case LDAP_RES_ADD:
-       case LDAP_RES_DELETE:
-       case LDAP_RES_MODDN:
-               if (ldap_parse_result(lldb->ldap, result, &handle->status,
-                                       &matcheddnp, &errmsgp,
-                                       &referralsp, &serverctrlsp, 0) != LDAP_SUCCESS) {
-                       handle->status = LDB_ERR_OPERATIONS_ERROR;
-                       goto error;
-               }
-               if (ac->callback && handle->status == LDB_SUCCESS) {
-                       ares = NULL; /* FIXME: build a corresponding ares to pass on */
-                       ret = ac->callback(ac->lldb->module->ldb, ac->context, ares);
-               }
-               handle->state = LDB_ASYNC_DONE;
+               request_done = true;
                break;
 
        default:
                ret = LDB_ERR_PROTOCOL_ERROR;
-               goto error;
+               break;
        }
 
+       if (ret != LDB_SUCCESS) {
+
+               /* if the callback failed the caller will have freed the
+                * request. Just return and don't try to use it */
+               if (callback_failed) {
+
+                       /* tell lldb_wait to remove the request from the
+                        *  queue */
+                       lret = true;
+                       goto free_and_return;
+               }
+
+               request_done = true;
+       }
+
+       if (request_done) {
+               lldb_request_done(ac->req, ac->controls, ret);
+               lret = true;
+               goto free_and_return;
+       }
+
+       lret = false;
+
+free_and_return:
+
        if (matcheddnp) ldap_memfree(matcheddnp);
        if (errmsgp && *errmsgp) {
-               ldb_set_errstring(ac->lldb->module->ldb, errmsgp);
-       } else if (handle->status) {
-               ldb_set_errstring(ac->lldb->module->ldb, ldap_err2string(handle->status));
+               ldb_set_errstring(ac->module->ldb, errmsgp);
        }
        if (errmsgp) {
                ldap_memfree(errmsgp);
@@ -633,131 +615,203 @@ static int lldb_parse_result(struct lldb_context *ac, LDAPMessage *result)
        if (serverctrlsp) ldap_controls_free(serverctrlsp);
 
        ldap_msgfree(result);
-       return lldb_ldap_to_ldb(handle->status);
 
-error:
-       handle->state = LDB_ASYNC_DONE;
-       ldap_msgfree(result);
-       return ret;
+       return lret;
 }
 
-static int lldb_wait(struct ldb_handle *handle, enum ldb_wait_type type)
+static void lldb_timeout(struct event_context *ev,
+                        struct timed_event *te,
+                        struct timeval t,
+                        void *private_data)
 {
-       struct lldb_context *ac = talloc_get_type(handle->private_data, struct lldb_context);
-       struct lldb_private *lldb = ac->lldb;
-       struct timeval timeout;
+       struct lldb_context *ac;
+       ac = talloc_get_type(private_data, struct lldb_context);
+
+       lldb_request_done(ac->req, NULL, LDB_ERR_TIME_LIMIT_EXCEEDED);
+}
+
+static void lldb_callback(struct event_context *ev,
+                         struct timed_event *te,
+                         struct timeval t,
+                         void *private_data)
+{
+       struct lldb_context *ac;
+       struct timed_event *lte;
+       struct timeval tv;
        LDAPMessage *result;
-       int ret, lret;
+       int lret;
+
+       ac = talloc_get_type(private_data, struct lldb_context);
 
-       if (handle->state == LDB_ASYNC_DONE) {
-               return handle->status;
+       if (!ac->msgid) {
+               lldb_request_done(ac->req, NULL, LDB_ERR_OPERATIONS_ERROR);
+               return;
        }
 
-       if (!ac || !ac->msgid) {
-               return LDB_ERR_OPERATIONS_ERROR;
+       tv.tv_sec = 0;
+       tv.tv_usec = 0;
+       lret = ldap_result(ac->lldb->ldap, ac->msgid, 0, &tv, &result);
+       if (lret == 0) {
+               goto respin;
+       }
+       if (lret == -1) {
+               lldb_request_done(ac->req, NULL, LDB_ERR_OPERATIONS_ERROR);
+               return;
        }
 
-       handle->state = LDB_ASYNC_PENDING;
-       handle->status = LDB_SUCCESS;
+       if ( ! lldb_parse_result(ac, result)) {
+               goto respin;
+       }
 
-       switch(type) {
-       case LDB_WAIT_NONE:
+       return;
 
-               if ((ac->timeout != -1) &&
-                   ((ac->starttime + ac->timeout) > time(NULL))) {
-                       return LDB_ERR_TIME_LIMIT_EXCEEDED;
-               }
+respin:
+       tv.tv_sec = 0;
+       tv.tv_usec = 100;
+       lte = event_add_timed(ev, ac, tv, lldb_callback, ac);
+       if (NULL == lte) {
+               lldb_request_done(ac->req, NULL, LDB_ERR_OPERATIONS_ERROR);
+       }
+}
 
-               timeout.tv_sec = 0;
-               timeout.tv_usec = 0;
+static bool lldb_dn_is_special(struct ldb_request *req)
+{
+       struct ldb_dn *dn = NULL;
 
-               lret = ldap_result(lldb->ldap, ac->msgid, 0, &timeout, &result);
-               if (lret == -1) {
-                       return LDB_ERR_OPERATIONS_ERROR;
-               }
-               if (lret == 0) {
-                       ret = LDB_SUCCESS;
-                       goto done;
-               }
+       switch (req->operation) {
+       case LDB_ADD:
+               dn = req->op.add.message->dn;
+               break;
+       case LDB_MODIFY:
+               dn = req->op.mod.message->dn;
+               break;
+       case LDB_DELETE:
+               dn = req->op.del.dn;
+               break;
+       case LDB_RENAME:
+               dn = req->op.rename.olddn;
+               break;
+       default:
+               break;
+       }
 
-               return lldb_parse_result(ac, result);
+       if (dn && ldb_dn_is_special(dn)) {
+               return true;
+       }
+       return false;
+}
 
-       case LDB_WAIT_ALL:
-               timeout.tv_usec = 0;
-               ret = LDB_ERR_OPERATIONS_ERROR;
+static void lldb_auto_done_callback(struct event_context *ev,
+                                   struct timed_event *te,
+                                   struct timeval t,
+                                   void *private_data)
+{
+       struct lldb_context *ac;
 
-               while (handle->status == LDB_SUCCESS && handle->state != LDB_ASYNC_DONE) {
+       ac = talloc_get_type(private_data, struct lldb_context);
+       lldb_request_done(ac->req, NULL, LDB_SUCCESS);
+}
 
-                       if (ac->timeout == -1) {
-                               lret = ldap_result(lldb->ldap, ac->msgid, 0, NULL, &result);
-                       } else {
-                               timeout.tv_sec = ac->timeout - (time(NULL) - ac->starttime);
-                               if (timeout.tv_sec <= 0)
-                                       return LDB_ERR_TIME_LIMIT_EXCEEDED;
-                               lret = ldap_result(lldb->ldap, ac->msgid, 0, &timeout, &result);
-                       }
-                       if (lret == -1) {
-                               return LDB_ERR_OPERATIONS_ERROR;
-                       }
-                       if (lret == 0) {
-                               return LDB_ERR_TIME_LIMIT_EXCEEDED;
-                       }
+static int lldb_handle_request(struct ldb_module *module, struct ldb_request *req)
+{
+       struct lldb_private *lldb;
+       struct lldb_context *ac;
+       struct event_context *ev;
+       struct timed_event *te;
+       struct timeval tv;
+       int ret;
 
-                       ret = lldb_parse_result(ac, result);
-                       if (ret != LDB_SUCCESS) {
-                               return ret;
-                       }
+       lldb = talloc_get_type(module->private_data, struct lldb_private);
+
+       if (req->starttime == 0 || req->timeout == 0) {
+               ldb_set_errstring(module->ldb, "Invalid timeout settings");
+               return LDB_ERR_TIME_LIMIT_EXCEEDED;
+       }
+
+       ev = ldb_get_event_context(module->ldb);
+       if (NULL == ev) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       ac = talloc_zero(module->ldb, struct lldb_context);
+       if (ac == NULL) {
+               ldb_set_errstring(module->ldb, "Out of Memory");
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       ac->module = module;
+       ac->req = req;
+       ac->lldb = lldb;
+       ac->msgid = 0;
+
+       if (lldb_dn_is_special(req)) {
+               tv.tv_sec = 0;
+               tv.tv_usec = 0;
+               te = event_add_timed(ev, ac, tv,
+                                    lldb_auto_done_callback, ac);
+               if (NULL == te) {
+                       return LDB_ERR_OPERATIONS_ERROR;
                }
 
+               return LDB_SUCCESS;
+       }
+
+       switch (ac->req->operation) {
+       case LDB_SEARCH:
+               ret = lldb_search(ac);
+               break;
+       case LDB_ADD:
+               ret = lldb_add(ac);
+               break;
+       case LDB_MODIFY:
+               ret = lldb_modify(ac);
+               break;
+       case LDB_DELETE:
+               ret = lldb_delete(ac);
+               break;
+       case LDB_RENAME:
+               ret = lldb_rename(ac);
                break;
-               
        default:
-               handle->state = LDB_ASYNC_DONE;
+               /* no other op supported */
                ret = LDB_ERR_OPERATIONS_ERROR;
+               break;
        }
 
-done:
-       return ret;
-}
-
-static int lldb_start_trans(struct ldb_module *module)
-{
-       /* TODO implement a local transaction mechanism here */
-
-       return LDB_SUCCESS;
-}
+       if (ret != LDB_SUCCESS) {
+               lldb_request_done(req, NULL, ret);
+               return ret;
+       }
 
-static int lldb_end_trans(struct ldb_module *module)
-{
-       /* TODO implement a local transaction mechanism here */
+       tv.tv_sec = 0;
+       tv.tv_usec = 0;
+       te = event_add_timed(ev, ac, tv, lldb_callback, ac);
+       if (NULL == te) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
 
-       return LDB_SUCCESS;
-}
 
-static int lldb_del_trans(struct ldb_module *module)
-{
-       /* TODO implement a local transaction mechanism here */
+       tv.tv_sec = req->starttime + req->timeout;
+       tv.tv_usec = 0;
+       te = event_add_timed(ev, ac, tv, lldb_timeout, ac);
+       if (NULL == te) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
 
        return LDB_SUCCESS;
 }
 
-static int lldb_request(struct ldb_module *module, struct ldb_request *req)
-{
-       return LDB_ERR_OPERATIONS_ERROR;
-}
-
 static const struct ldb_module_ops lldb_ops = {
        .name              = "ldap",
-       .search            = lldb_search,
-       .add               = lldb_add,
-       .modify            = lldb_modify,
-       .del               = lldb_delete,
-       .rename            = lldb_rename,
-       .request           = lldb_request,
+       .search            = lldb_handle_request,
+       .add               = lldb_handle_request,
+       .modify            = lldb_handle_request,
+       .del               = lldb_handle_request,
+       .rename            = lldb_handle_request,
+       .request           = lldb_handle_request,
        .start_transaction = lldb_start_trans,
        .end_transaction   = lldb_end_trans,
        .del_transaction   = lldb_del_trans,
-       .wait              = lldb_wait
 };
 
 
@@ -771,8 +825,8 @@ static int lldb_destructor(struct lldb_private *lldb)
   connect to the database
 */
 static int lldb_connect(struct ldb_context *ldb,
-                       const char *url, 
-                       unsigned int flags, 
+                       const char *url,
+                       unsigned int flags,
                        const char *options[],
                        struct ldb_module **_module)
 {
@@ -790,7 +844,6 @@ static int lldb_connect(struct ldb_context *ldb,
        talloc_set_name_const(module, "ldb_ldap backend");
        module->ldb             = ldb;
        module->prev            = module->next = NULL;
-       module->private_data    = NULL;
        module->ops             = &lldb_ops;
 
        lldb = talloc(module, struct lldb_private);
@@ -799,7 +852,6 @@ static int lldb_connect(struct ldb_context *ldb,
                goto failed;
        }
        module->private_data    = lldb;
-       lldb->module            = module;
        lldb->ldap              = NULL;
 
        ret = ldap_initialize(&lldb->ldap, url);
index e9129c812b27cd354aea138a693ac3c53646c7c9..fafbb63b0a7c55ca8ebd2818555f68c5985afe1a 100644 (file)
@@ -3,6 +3,7 @@
 
    Copyright (C) Jelmer Vernooij 2005
    Copyright (C) Martin Kuehl <mkhl@samba.org> 2006
+   Copyright (C) Simo Sorce 2008
 
      ** NOTE! The following LGPL license applies to the ldb
      ** library. This does NOT imply that all of Samba is released
@@ -106,69 +107,23 @@ const struct ldb_map_context *map_get_context(struct ldb_module *module)
 }
 
 /* Create a generic request context. */
-static struct map_context *map_init_context(struct ldb_handle *h, struct ldb_request *req)
+struct map_context *map_init_context(struct ldb_module *module,
+                                       struct ldb_request *req)
 {
        struct map_context *ac;
 
-       ac = talloc_zero(h, struct map_context);
+       ac = talloc_zero(req, struct map_context);
        if (ac == NULL) {
-               map_oom(h->module);
+               ldb_set_errstring(module->ldb, "Out of Memory");
                return NULL;
        }
 
-       ac->module = h->module;
-       ac->orig_req = req;
+       ac->module = module;
+       ac->req = req;
 
        return ac;
 }
 
-/* Create a search request context. */
-struct map_search_context *map_init_search_context(struct map_context *ac, struct ldb_reply *ares)
-{
-       struct map_search_context *sc;
-
-       sc = talloc_zero(ac, struct map_search_context);
-       if (sc == NULL) {
-               map_oom(ac->module);
-               return NULL;
-       }
-
-       sc->ac = ac;
-       sc->local_res = NULL;
-       sc->remote_res = ares;
-
-       return sc;
-}
-
-/* Create a request context and handle. */
-struct ldb_handle *map_init_handle(struct ldb_request *req, struct ldb_module *module)
-{
-       struct map_context *ac;
-       struct ldb_handle *h;
-
-       h = talloc_zero(req, struct ldb_handle);
-       if (h == NULL) {
-               map_oom(module);
-               return NULL;
-       }
-
-       h->module = module;
-
-       ac = map_init_context(h, req);
-       if (ac == NULL) {
-               talloc_free(h);
-               return NULL;
-       }
-
-       h->private_data = (void *)ac;
-
-       h->state = LDB_ASYNC_INIT;
-       h->status = LDB_SUCCESS;
-
-       return h;
-}
-
-
 /* Dealing with DNs for different partitions
  * ========================================= */
 
@@ -888,113 +843,52 @@ static int map_objectclass_convert_operator(struct ldb_module *module, void *mem
 /* Auxiliary request construction
  * ============================== */
 
-/* Store the DN of a single search result in context. */
-static int map_search_self_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares)
-{
-       struct map_context *ac;
-
-       if (context == NULL || ares == NULL) {
-               ldb_set_errstring(ldb, talloc_asprintf(ldb, "NULL Context or Result in callback"));
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       ac = talloc_get_type(context, struct map_context);
-
-       /* We are interested only in the single reply */
-       if (ares->type != LDB_REPLY_ENTRY) {
-               talloc_free(ares);
-               return LDB_SUCCESS;
-       }
-
-       /* We have already found a remote DN */
-       if (ac->local_dn) {
-               ldb_set_errstring(ldb, talloc_asprintf(ldb, "Too many results to base search"));
-               talloc_free(ares);
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       /* Store local DN */
-       ac->local_dn = ares->message->dn;
-
-       return LDB_SUCCESS;
-}
-
 /* Build a request to search a record by its DN. */
-struct ldb_request *map_search_base_req(struct map_context *ac, struct ldb_dn *dn, const char * const *attrs, const struct ldb_parse_tree *tree, void *context, ldb_search_callback callback)
+struct ldb_request *map_search_base_req(struct map_context *ac, struct ldb_dn *dn, const char * const *attrs, const struct ldb_parse_tree *tree, void *context, ldb_map_callback_t callback)
 {
+       const struct ldb_parse_tree *search_tree;
        struct ldb_request *req;
-
-       req = talloc_zero(ac, struct ldb_request);
-       if (req == NULL) {
-               map_oom(ac->module);
-               return NULL;
-       }
-
-       req->operation = LDB_SEARCH;
-       req->op.search.base = dn;
-       req->op.search.scope = LDB_SCOPE_BASE;
-       req->op.search.attrs = attrs;
+       int ret;
 
        if (tree) {
-               req->op.search.tree = tree;
+               search_tree = tree;
        } else {
-               req->op.search.tree = ldb_parse_tree(req, NULL);
-               if (req->op.search.tree == NULL) {
-                       talloc_free(req);
+               search_tree = ldb_parse_tree(ac, NULL);
+               if (search_tree == NULL) {
                        return NULL;
                }
        }
 
-       req->controls = NULL;
-       req->context = context;
-       req->callback = callback;
-       ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, req);
-
-       return req;
-}
-
-/* Build a request to search the local record by its DN. */
-struct ldb_request *map_search_self_req(struct map_context *ac, struct ldb_dn *dn)
-{
-       /* attrs[] is returned from this function in
-        * ac->search_req->op.search.attrs, so it must be static, as
-        * otherwise the compiler can put it on the stack */
-       static const char * const attrs[] = { IS_MAPPED, NULL };
-       struct ldb_parse_tree *tree;
-
-       /* Limit search to records with 'IS_MAPPED' present */
-       /* TODO: `tree = ldb_parse_tree(ac, IS_MAPPED);' won't do. */
-       tree = talloc_zero(ac, struct ldb_parse_tree);
-       if (tree == NULL) {
-               map_oom(ac->module);
+       ret = ldb_build_search_req_ex(&req, ac->module->ldb, ac,
+                                       dn, LDB_SCOPE_BASE,
+                                       search_tree, attrs,
+                                       NULL,
+                                       context, callback,
+                                       ac->req);
+       if (ret != LDB_SUCCESS) {
                return NULL;
        }
 
-       tree->operation = LDB_OP_PRESENT;
-       tree->u.present.attr = talloc_strdup(tree, IS_MAPPED);
-
-       return map_search_base_req(ac, dn, attrs, tree, ac, map_search_self_callback);
+       return req;
 }
 
 /* Build a request to update the 'IS_MAPPED' attribute */
-struct ldb_request *map_build_fixup_req(struct map_context *ac, struct ldb_dn *olddn, struct ldb_dn *newdn)
+struct ldb_request *map_build_fixup_req(struct map_context *ac,
+                                       struct ldb_dn *olddn,
+                                       struct ldb_dn *newdn,
+                                       void *context,
+                                       ldb_map_callback_t callback)
 {
        struct ldb_request *req;
        struct ldb_message *msg;
        const char *dn;
-
-       /* Prepare request */
-       req = talloc_zero(ac, struct ldb_request);
-       if (req == NULL) {
-               map_oom(ac->module);
-               return NULL;
-       }
+       int ret;
 
        /* Prepare message */
-       msg = ldb_msg_new(req);
+       msg = ldb_msg_new(ac);
        if (msg == NULL) {
                map_oom(ac->module);
-               goto failed;
+               return NULL;
        }
 
        /* Update local 'IS_MAPPED' to the new remote DN */
@@ -1010,193 +904,22 @@ struct ldb_request *map_build_fixup_req(struct map_context *ac, struct ldb_dn *o
                goto failed;
        }
 
-       req->operation = LDB_MODIFY;
-       req->op.mod.message = msg;
-       req->controls = NULL;
-       req->handle = NULL;
-       req->context = NULL;
-       req->callback = NULL;
+       /* Prepare request */
+       ret = ldb_build_mod_req(&req, ac->module->ldb,
+                               ac, msg, NULL,
+                               context, callback,
+                               ac->req);
+       if (ret != LDB_SUCCESS) {
+               goto failed;
+       }
+       talloc_steal(req, msg);
 
        return req;
-
 failed:
-       talloc_free(req);
+       talloc_free(msg);
        return NULL;
 }
 
-
-/* Asynchronous call structure
- * =========================== */
-
-/* Figure out which request is currently pending. */
-static struct ldb_request *map_get_req(struct map_context *ac)
-{
-       switch (ac->step) {
-       case MAP_SEARCH_SELF_MODIFY:
-       case MAP_SEARCH_SELF_DELETE:
-       case MAP_SEARCH_SELF_RENAME:
-               return ac->search_req;
-
-       case MAP_ADD_REMOTE:
-       case MAP_MODIFY_REMOTE:
-       case MAP_DELETE_REMOTE:
-       case MAP_RENAME_REMOTE:
-               return ac->remote_req;
-
-       case MAP_RENAME_FIXUP:
-               return ac->down_req;
-
-       case MAP_ADD_LOCAL:
-       case MAP_MODIFY_LOCAL:
-       case MAP_DELETE_LOCAL:
-       case MAP_RENAME_LOCAL:
-               return ac->local_req;
-
-       case MAP_SEARCH_REMOTE:
-               /* Can't happen */
-               break;
-       }
-
-       return NULL;            /* unreachable; silences a warning */
-}
-
-typedef int (*map_next_function)(struct ldb_handle *handle);
-
-/* Figure out the next request to run. */
-static map_next_function map_get_next(struct map_context *ac)
-{
-       switch (ac->step) {
-       case MAP_SEARCH_REMOTE:
-               return NULL;
-
-       case MAP_ADD_LOCAL:
-               return map_add_do_remote;
-       case MAP_ADD_REMOTE:
-               return NULL;
-
-       case MAP_SEARCH_SELF_MODIFY:
-               return map_modify_do_local;
-       case MAP_MODIFY_LOCAL:
-               return map_modify_do_remote;
-       case MAP_MODIFY_REMOTE:
-               return NULL;
-
-       case MAP_SEARCH_SELF_DELETE:
-               return map_delete_do_local;
-       case MAP_DELETE_LOCAL:
-               return map_delete_do_remote;
-       case MAP_DELETE_REMOTE:
-               return NULL;
-
-       case MAP_SEARCH_SELF_RENAME:
-               return map_rename_do_local;
-       case MAP_RENAME_LOCAL:
-               return map_rename_do_fixup;
-       case MAP_RENAME_FIXUP:
-               return map_rename_do_remote;
-       case MAP_RENAME_REMOTE:
-               return NULL;
-       }
-
-       return NULL;            /* unreachable; silences a warning */
-}
-
-/* Wait for the current pending request to finish and continue with the next. */
-static int map_wait_next(struct ldb_handle *handle)
-{
-       struct map_context *ac;
-       struct ldb_request *req;
-       map_next_function next;
-       int ret;
-
-       if (handle == NULL || handle->private_data == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       if (handle->state == LDB_ASYNC_DONE) {
-               return handle->status;
-       }
-
-       handle->state = LDB_ASYNC_PENDING;
-       handle->status = LDB_SUCCESS;
-
-       ac = talloc_get_type(handle->private_data, struct map_context);
-
-       if (ac->step == MAP_SEARCH_REMOTE) {
-               int i;
-               for (i = 0; i < ac->num_searches; i++) {
-                       req = ac->search_reqs[i];
-                       ret = ldb_wait(req->handle, LDB_WAIT_NONE);
-
-                       if (ret != LDB_SUCCESS) {
-                               handle->status = ret;
-                               goto done;
-                       }
-                       if (req->handle->status != LDB_SUCCESS) {
-                               handle->status = req->handle->status;
-                               goto done;
-                       }
-                       if (req->handle->state != LDB_ASYNC_DONE) {
-                               return LDB_SUCCESS;
-                       }
-               }
-       } else {
-
-               req = map_get_req(ac);
-
-               ret = ldb_wait(req->handle, LDB_WAIT_NONE);
-
-               if (ret != LDB_SUCCESS) {
-                       handle->status = ret;
-                       goto done;
-               }
-               if (req->handle->status != LDB_SUCCESS) {
-                       handle->status = req->handle->status;
-                       goto done;
-               }
-               if (req->handle->state != LDB_ASYNC_DONE) {
-                       return LDB_SUCCESS;
-               }
-
-               next = map_get_next(ac);
-               if (next) {
-                       return next(handle);
-               }
-       }
-
-       ret = LDB_SUCCESS;
-
-done:
-       handle->state = LDB_ASYNC_DONE;
-       return ret;
-}
-
-/* Wait for all current pending requests to finish. */
-static int map_wait_all(struct ldb_handle *handle)
-{
-       int ret;
-
-       while (handle->state != LDB_ASYNC_DONE) {
-               ret = map_wait_next(handle);
-               if (ret != LDB_SUCCESS) {
-                       return ret;
-               }
-       }
-
-       return handle->status;
-}
-
-/* Wait for pending requests to finish. */
-int map_wait(struct ldb_handle *handle, enum ldb_wait_type type)
-{
-       if (type == LDB_WAIT_ALL) {
-               return map_wait_all(handle);
-       } else {
-               return map_wait_next(handle);
-       }
-}
-
-
 /* Module initialization
  * ===================== */
 
index e40bb9cd7e3aadb5a9d02eb204fbf7c085ded130..7f92c15b986b1cff4bad1e5bb7805d2da3f8811f 100644 (file)
@@ -160,14 +160,12 @@ int map_search(struct ldb_module *module, struct ldb_request *req);
 int map_rename(struct ldb_module *module, struct ldb_request *req);
 int map_delete(struct ldb_module *module, struct ldb_request *req);
 int map_modify(struct ldb_module *module, struct ldb_request *req);
-int map_wait(struct ldb_handle *handle, enum ldb_wait_type type);
 
 #define LDB_MAP_OPS \
        .add            = map_add, \
        .modify         = map_modify, \
        .del            = map_delete, \
        .rename         = map_rename, \
-       .search         = map_search, \
-       .wait           = map_wait,
+       .search         = map_search,
 
 #endif /* __LDB_MAP_H__ */
index 7fc3ac4ed5ee660b8d78d44526f8c5671617517e..96605f23ebcc0214405f87aaa0da45e011871eab 100644 (file)
@@ -3,6 +3,7 @@
 
    Copyright (C) Jelmer Vernooij 2005
    Copyright (C) Martin Kuehl <mkhl@samba.org> 2006
+   Copyright (C) Simo Sorce <idra@samba.org> 2008
 
      ** NOTE! The following LGPL license applies to the ldb
      ** library. This does NOT imply that all of Samba is released
@@ -178,51 +179,181 @@ static int ldb_msg_partition(struct ldb_module *module, struct ldb_message *loca
 }
 
 
-/* Inbound requests: add, modify, rename, delete
- * ============================================= */
+static int map_add_do_local(struct map_context *ac);
+static int map_modify_do_local(struct map_context *ac);
+static int map_delete_do_local(struct map_context *ac);
+static int map_rename_do_local(struct map_context *ac);
+static int map_rename_do_fixup(struct map_context *ac);
+static int map_rename_local_callback(struct ldb_request *req,
+                                    struct ldb_reply *ares);
 
-/* Add the remote record. */
-int map_add_do_remote(struct ldb_handle *handle)
+
+/*****************************************************************************
+ * COMMON INBOUND functions
+*****************************************************************************/
+
+/* Store the DN of a single search result in context. */
+static int map_search_self_callback(struct ldb_request *req, struct ldb_reply *ares)
 {
        struct map_context *ac;
+       int ret;
 
-       ac = talloc_get_type(handle->private_data, struct map_context);
+       ac = talloc_get_type(req->context, struct map_context);
 
-       ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->remote_req);
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
 
-       ac->step = MAP_ADD_REMOTE;
+       /* We are interested only in the single reply */
+       switch(ares->type) {
+       case LDB_REPLY_ENTRY:
+               /* We have already found a remote DN */
+               if (ac->local_dn) {
+                       ldb_set_errstring(ac->module->ldb,
+                                         "Too many results!");
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
+               }
 
-       handle->state = LDB_ASYNC_INIT;
-       handle->status = LDB_SUCCESS;
+               /* Store local DN */
+               ac->local_dn = talloc_steal(ac, ares->message->dn);
+               break;
 
-       return ldb_next_remote_request(ac->module, ac->remote_req);
+       case LDB_REPLY_DONE:
+
+               switch (ac->req->operation) {
+               case LDB_MODIFY:
+                       ret = map_modify_do_local(ac);
+                       break;
+               case LDB_DELETE:
+                       ret = map_delete_do_local(ac);
+                       break;
+               case LDB_RENAME:
+                       ret = map_rename_do_local(ac);
+                       break;
+               default:
+                       /* if we get here we have definitely a problem */
+                       ret = LDB_ERR_OPERATIONS_ERROR;
+               }
+               if (ret != LDB_SUCCESS) {
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
+               }
+
+       default:
+               /* ignore referrals */
+               break;
+       }
+
+       talloc_free(ares);
+       return LDB_SUCCESS;
 }
 
-/* Add the local record. */
-int map_add_do_local(struct ldb_handle *handle)
+/* Build a request to search the local record by its DN. */
+static int map_search_self_req(struct ldb_request **req,
+                               struct map_context *ac,
+                               struct ldb_dn *dn)
+{
+       /* attrs[] is returned from this function in
+        * ac->search_req->op.search.attrs, so it must be static, as
+        * otherwise the compiler can put it on the stack */
+       static const char * const attrs[] = { IS_MAPPED, NULL };
+       struct ldb_parse_tree *tree;
+
+       /* Limit search to records with 'IS_MAPPED' present */
+       tree = ldb_parse_tree(ac, "(" IS_MAPPED "=*)");
+       if (tree == NULL) {
+               map_oom(ac->module);
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       *req = map_search_base_req(ac, dn, attrs, tree,
+                                  ac, map_search_self_callback);
+       if (*req == NULL) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       return LDB_SUCCESS;
+}
+
+static int map_op_local_callback(struct ldb_request *req,
+                                struct ldb_reply *ares)
 {
        struct map_context *ac;
+       int ret;
 
-       ac = talloc_get_type(handle->private_data, struct map_context);
+       ac = talloc_get_type(req->context, struct map_context);
 
-       ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->local_req);
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
 
-       ac->step = MAP_ADD_LOCAL;
+       if (ares->type != LDB_REPLY_DONE) {
+               ldb_set_errstring(req->handle->ldb, "Invalid reply type!");
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
 
-       handle->state = LDB_ASYNC_INIT;
-       handle->status = LDB_SUCCESS;
+       /* Do the remote request. */
+       ret = ldb_next_remote_request(ac->module, ac->remote_req);
+       if (ret != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
 
-       return ldb_next_request(ac->module, ac->local_req);
+       return LDB_SUCCESS;
 }
 
+static int map_op_remote_callback(struct ldb_request *req,
+                                 struct ldb_reply *ares)
+{
+       struct map_context *ac;
+
+       ac = talloc_get_type(req->context, struct map_context);
+
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
+
+       if (ares->type != LDB_REPLY_DONE) {
+               ldb_set_errstring(req->handle->ldb, "Invalid reply type!");
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+
+       return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+}
+
+
+/*****************************************************************************
+ * ADD operations
+*****************************************************************************/
+
+
 /* Add a record. */
 int map_add(struct ldb_module *module, struct ldb_request *req)
 {
        const struct ldb_message *msg = req->op.add.message;
-       struct ldb_handle *h;
        struct map_context *ac;
-       struct ldb_message *local, *remote;
+       struct ldb_message *remote_msg;
        const char *dn;
+       int ret;
 
        /* Do not manipulate our control entries */
        if (ldb_dn_is_special(msg->dn)) {
@@ -240,141 +371,88 @@ int map_add(struct ldb_module *module, struct ldb_request *req)
        }
 
        /* Prepare context and handle */
-       h = map_init_handle(req, module);
-       if (h == NULL) {
+       ac = map_init_context(module, req);
+       if (ac == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       ac = talloc_get_type(h->private_data, struct map_context);
-
-       /* Prepare the local operation */
-       ac->local_req = talloc(ac, struct ldb_request);
-       if (ac->local_req == NULL) {
-               goto oom;
-       }
 
-       *(ac->local_req) = *req;        /* copy the request */
-
-       ac->local_req->context = NULL;
-       ac->local_req->callback = NULL;
-
-       /* Prepare the remote operation */
-       ac->remote_req = talloc(ac, struct ldb_request);
-       if (ac->remote_req == NULL) {
-               goto oom;
-       }
-
-       *(ac->remote_req) = *req;       /* copy the request */
-
-       ac->remote_req->context = NULL;
-       ac->remote_req->callback = NULL;
 
        /* Prepare the local message */
-       local = ldb_msg_new(ac->local_req);
-       if (local == NULL) {
-               goto oom;
+       ac->local_msg = ldb_msg_new(ac);
+       if (ac->local_msg == NULL) {
+               map_oom(module);
+               return LDB_ERR_OPERATIONS_ERROR;
        }
-       local->dn = msg->dn;
+       ac->local_msg->dn = msg->dn;
 
        /* Prepare the remote message */
-       remote = ldb_msg_new(ac->remote_req);
-       if (remote == NULL) {
-               goto oom;
+       remote_msg = ldb_msg_new(ac);
+       if (remote_msg == NULL) {
+               map_oom(module);
+               return LDB_ERR_OPERATIONS_ERROR;
        }
-       remote->dn = ldb_dn_map_local(ac->module, remote, msg->dn);
+       remote_msg->dn = ldb_dn_map_local(ac->module, remote_msg, msg->dn);
 
        /* Split local from remote message */
-       ldb_msg_partition(module, local, remote, msg);
-       ac->local_req->op.add.message = local;
-       ac->remote_req->op.add.message = remote;
+       ldb_msg_partition(module, ac->local_msg, remote_msg, msg);
+
+       /* Prepare the remote operation */
+       ret = ldb_build_add_req(&ac->remote_req, module->ldb,
+                               ac, remote_msg,
+                               req->controls,
+                               ac, map_op_remote_callback,
+                               req);
+       if (ret != LDB_SUCCESS) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
 
-       if ((local->num_elements == 0) || (!map_check_local_db(ac->module))) {
+       if ((ac->local_msg->num_elements == 0) ||
+           ( ! map_check_local_db(ac->module))) {
                /* No local data or db, just run the remote request */
-               talloc_free(ac->local_req);
-               req->handle = h;        /* return our own handle to deal with this call */
-               return map_add_do_remote(h);
+               return ldb_next_remote_request(ac->module, ac->remote_req);
        }
 
        /* Store remote DN in 'IS_MAPPED' */
        /* TODO: use GUIDs here instead */
-       dn = ldb_dn_alloc_linearized(local, remote->dn);
-       if (ldb_msg_add_string(local, IS_MAPPED, dn) != 0) {
-               goto failed;
+       dn = ldb_dn_alloc_linearized(ac->local_msg, remote_msg->dn);
+       if (ldb_msg_add_string(ac->local_msg, IS_MAPPED, dn) != 0) {
+               return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       req->handle = h;                /* return our own handle to deal with this call */
-       return map_add_do_local(h);
-
-oom:
-       map_oom(module);
-failed:
-       talloc_free(h);
-       return LDB_ERR_OPERATIONS_ERROR;
-}
-
-/* Modify the remote record. */
-int map_modify_do_remote(struct ldb_handle *handle)
-{
-       struct map_context *ac;
-
-       ac = talloc_get_type(handle->private_data, struct map_context);
-
-       ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->remote_req);
-
-       ac->step = MAP_MODIFY_REMOTE;
-
-       handle->state = LDB_ASYNC_INIT;
-       handle->status = LDB_SUCCESS;
-
-       return ldb_next_remote_request(ac->module, ac->remote_req);
+       return map_add_do_local(ac);
 }
 
-/* Modify the local record. */
-int map_modify_do_local(struct ldb_handle *handle)
+/* Add the local record. */
+static int map_add_do_local(struct map_context *ac)
 {
-       struct map_context *ac;
-       struct ldb_message *msg;
-       char *dn;
-
-       ac = talloc_get_type(handle->private_data, struct map_context);
-
-       if (ac->local_dn == NULL) {
-               /* No local record present, add it instead */
-               msg = discard_const_p(struct ldb_message, ac->local_req->op.mod.message);
-
-               /* Add local 'IS_MAPPED' */
-               /* TODO: use GUIDs here instead */
-               if (ldb_msg_add_empty(msg, IS_MAPPED, LDB_FLAG_MOD_ADD, NULL) != 0) {
-                       return LDB_ERR_OPERATIONS_ERROR;
-               }
-               dn = ldb_dn_alloc_linearized(msg, ac->remote_req->op.mod.message->dn);
-               if (ldb_msg_add_string(msg, IS_MAPPED, dn) != 0) {
-                       return LDB_ERR_OPERATIONS_ERROR;
-               }
+       struct ldb_request *local_req;
+       int ret;
 
-               /* Turn request into 'add' */
-               ac->local_req->operation = LDB_ADD;
-               ac->local_req->op.add.message = msg;
-               /* TODO: Could I just leave msg in there?  I think so,
-                *       but it looks clearer this way. */
+       /* Prepare the local operation */
+       ret = ldb_build_add_req(&local_req, ac->module->ldb, ac,
+                               ac->local_msg,
+                               ac->req->controls,
+                               ac,
+                               map_op_local_callback,
+                               ac->req);
+       if (ret != LDB_SUCCESS) {
+               return LDB_ERR_OPERATIONS_ERROR;
        }
-
-       ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->local_req);
-
-       ac->step = MAP_MODIFY_LOCAL;
-
-       handle->state = LDB_ASYNC_INIT;
-       handle->status = LDB_SUCCESS;
-
-       return ldb_next_request(ac->module, ac->local_req);
+       return ldb_next_request(ac->module, local_req);
 }
 
+/*****************************************************************************
+ * MODIFY operations
+*****************************************************************************/
+
 /* Modify a record. */
 int map_modify(struct ldb_module *module, struct ldb_request *req)
 {
        const struct ldb_message *msg = req->op.mod.message;
-       struct ldb_handle *h;
+       struct ldb_request *search_req;
+       struct ldb_message *remote_msg;
        struct map_context *ac;
-       struct ldb_message *local, *remote;
+       int ret;
 
        /* Do not manipulate our control entries */
        if (ldb_dn_is_special(msg->dn)) {
@@ -395,257 +473,200 @@ int map_modify(struct ldb_module *module, struct ldb_request *req)
        }
 
        /* Prepare context and handle */
-       h = map_init_handle(req, module);
-       if (h == NULL) {
+       ac = map_init_context(module, req);
+       if (ac == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       ac = talloc_get_type(h->private_data, struct map_context);
-
-       /* Prepare the local operation */
-       ac->local_req = talloc(ac, struct ldb_request);
-       if (ac->local_req == NULL) {
-               goto oom;
-       }
-
-       *(ac->local_req) = *req;        /* copy the request */
-
-       ac->local_req->context = NULL;
-       ac->local_req->callback = NULL;
-
-       /* Prepare the remote operation */
-       ac->remote_req = talloc(ac, struct ldb_request);
-       if (ac->remote_req == NULL) {
-               goto oom;
-       }
-
-       *(ac->remote_req) = *req;       /* copy the request */
-
-       ac->remote_req->context = NULL;
-       ac->remote_req->callback = NULL;
 
        /* Prepare the local message */
-       local = ldb_msg_new(ac->local_req);
-       if (local == NULL) {
-               goto oom;
+       ac->local_msg = ldb_msg_new(ac);
+       if (ac->local_msg == NULL) {
+               map_oom(module);
+               return LDB_ERR_OPERATIONS_ERROR;
        }
-       local->dn = msg->dn;
+       ac->local_msg->dn = msg->dn;
 
        /* Prepare the remote message */
-       remote = ldb_msg_new(ac->remote_req);
-       if (remote == NULL) {
-               goto oom;
+       remote_msg = ldb_msg_new(ac->remote_req);
+       if (remote_msg == NULL) {
+               map_oom(module);
+               return LDB_ERR_OPERATIONS_ERROR;
        }
-       remote->dn = ldb_dn_map_local(ac->module, remote, msg->dn);
+       remote_msg->dn = ldb_dn_map_local(ac->module, remote_msg, msg->dn);
 
        /* Split local from remote message */
-       ldb_msg_partition(module, local, remote, msg);
-       ac->local_req->op.mod.message = local;
-       ac->remote_req->op.mod.message = remote;
+       ldb_msg_partition(module, ac->local_msg, remote_msg, msg);
+
+       /* Prepare the remote operation */
+       ret = ldb_build_mod_req(&ac->remote_req, module->ldb,
+                               ac, remote_msg,
+                               req->controls,
+                               ac, map_op_remote_callback,
+                               req);
+       if (ret != LDB_SUCCESS) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
 
-       if ((local->num_elements == 0) || (!map_check_local_db(ac->module))) {
+       if ((ac->local_msg->num_elements == 0) ||
+           ( ! map_check_local_db(ac->module))) {
                /* No local data or db, just run the remote request */
-               talloc_free(ac->local_req);
-               req->handle = h;        /* return our own handle to deal with this call */
-               return map_modify_do_remote(h);
+               return ldb_next_remote_request(ac->module, ac->remote_req);
        }
 
        /* prepare the search operation */
-       ac->search_req = map_search_self_req(ac, msg->dn);
-       if (ac->search_req == NULL) {
-               goto failed;
+       ret = map_search_self_req(&search_req, ac, msg->dn);
+       if (ret != LDB_SUCCESS) {
+               return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       ac->step = MAP_SEARCH_SELF_MODIFY;
-
-       req->handle = h;                /* return our own handle to deal with this call */
-       return ldb_next_request(module, ac->search_req);
-
-oom:
-       map_oom(module);
-failed:
-       talloc_free(h);
-       return LDB_ERR_OPERATIONS_ERROR;
-}
-
-/* Delete the remote record. */
-int map_delete_do_remote(struct ldb_handle *handle)
-{
-       struct map_context *ac;
-
-       ac = talloc_get_type(handle->private_data, struct map_context);
-
-       ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->remote_req);
-
-       ac->step = MAP_DELETE_REMOTE;
-
-       handle->state = LDB_ASYNC_INIT;
-       handle->status = LDB_SUCCESS;
-
-       return ldb_next_remote_request(ac->module, ac->remote_req);
+       return ldb_next_request(module, search_req);
 }
 
-/* Delete the local record. */
-int map_delete_do_local(struct ldb_handle *handle)
+/* Modify the local record. */
+static int map_modify_do_local(struct map_context *ac)
 {
-       struct map_context *ac;
-
-       ac = talloc_get_type(handle->private_data, struct map_context);
+       struct ldb_request *local_req;
+       char *dn;
+       int ret;
 
-       /* No local record, continue remotely */
        if (ac->local_dn == NULL) {
-               return map_delete_do_remote(handle);
-       }
-
-       ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->local_req);
-
-       ac->step = MAP_DELETE_LOCAL;
+               /* No local record present, add it instead */
+               /* Add local 'IS_MAPPED' */
+               /* TODO: use GUIDs here instead */
+               if (ldb_msg_add_empty(ac->local_msg, IS_MAPPED,
+                                       LDB_FLAG_MOD_ADD, NULL) != 0) {
+                       return LDB_ERR_OPERATIONS_ERROR;
+               }
+               dn = ldb_dn_alloc_linearized(ac->local_msg,
+                                       ac->remote_req->op.mod.message->dn);
+               if (ldb_msg_add_string(ac->local_msg, IS_MAPPED, dn) != 0) {
+                       return LDB_ERR_OPERATIONS_ERROR;
+               }
 
-       handle->state = LDB_ASYNC_INIT;
-       handle->status = LDB_SUCCESS;
+               /* Prepare the local operation */
+               ret = ldb_build_add_req(&local_req, ac->module->ldb, ac,
+                                       ac->local_msg,
+                                       ac->req->controls,
+                                       ac,
+                                       map_op_local_callback,
+                                       ac->req);
+               if (ret != LDB_SUCCESS) {
+                       return LDB_ERR_OPERATIONS_ERROR;
+               }
+       } else {
+               /* Prepare the local operation */
+               ret = ldb_build_mod_req(&local_req, ac->module->ldb, ac,
+                                       ac->local_msg,
+                                       ac->req->controls,
+                                       ac,
+                                       map_op_local_callback,
+                                       ac->req);
+               if (ret != LDB_SUCCESS) {
+                       return LDB_ERR_OPERATIONS_ERROR;
+               }
+       }
 
-       return ldb_next_request(ac->module, ac->local_req);
+       return ldb_next_request(ac->module, local_req);
 }
 
+/*****************************************************************************
+ * DELETE operations
+*****************************************************************************/
+
 /* Delete a record. */
 int map_delete(struct ldb_module *module, struct ldb_request *req)
 {
-       struct ldb_handle *h;
+       struct ldb_request *search_req;
        struct map_context *ac;
+       int ret;
 
        /* Do not manipulate our control entries */
        if (ldb_dn_is_special(req->op.del.dn)) {
                return ldb_next_request(module, req);
        }
 
-       /* No mapping requested (perhaps no DN mapping specified), skip to next module */
+       /* No mapping requested (perhaps no DN mapping specified).
+        * Skip to next module */
        if (!ldb_dn_check_local(module, req->op.del.dn)) {
                return ldb_next_request(module, req);
        }
 
        /* Prepare context and handle */
-       h = map_init_handle(req, module);
-       if (h == NULL) {
+       ac = map_init_context(module, req);
+       if (ac == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       ac = talloc_get_type(h->private_data, struct map_context);
-
-       /* Prepare the local operation */
-       ac->local_req = talloc(ac, struct ldb_request);
-       if (ac->local_req == NULL) {
-               goto oom;
-       }
-
-       *(ac->local_req) = *req;        /* copy the request */
-       ac->local_req->op.del.dn = req->op.del.dn;
-
-       ac->local_req->context = NULL;
-       ac->local_req->callback = NULL;
 
        /* Prepare the remote operation */
-       ac->remote_req = talloc(ac, struct ldb_request);
-       if (ac->remote_req == NULL) {
-               goto oom;
+       ret = ldb_build_del_req(&ac->remote_req, module->ldb, ac,
+                                  ldb_dn_map_local(module, ac, req->op.del.dn),
+                                  req->controls,
+                                  ac,
+                                  map_op_remote_callback,
+                                  req);
+       if (ret != LDB_SUCCESS) {
+               return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       *(ac->remote_req) = *req;       /* copy the request */
-       ac->remote_req->op.del.dn = ldb_dn_map_local(module, ac->remote_req, req->op.del.dn);
-
        /* No local db, just run the remote request */
        if (!map_check_local_db(ac->module)) {
-               req->handle = h;        /* return our own handle to deal with this call */
-               return map_delete_do_remote(h);
+               /* Do the remote request. */
+               return ldb_next_remote_request(ac->module, ac->remote_req);
        }
 
-       ac->remote_req->context = NULL;
-       ac->remote_req->callback = NULL;
-
        /* Prepare the search operation */
-       ac->search_req = map_search_self_req(ac, req->op.del.dn);
-       if (ac->search_req == NULL) {
-               goto failed;
+       ret = map_search_self_req(&search_req, ac, req->op.del.dn);
+       if (ret != LDB_SUCCESS) {
+               map_oom(module);
+               return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       req->handle = h;                /* return our own handle to deal with this call */
-
-       ac->step = MAP_SEARCH_SELF_DELETE;
-
-       return ldb_next_request(module, ac->search_req);
-
-oom:
-       map_oom(module);
-failed:
-       talloc_free(h);
-       return LDB_ERR_OPERATIONS_ERROR;
+       return ldb_next_request(module, search_req);
 }
 
-/* Rename the remote record. */
-int map_rename_do_remote(struct ldb_handle *handle)
-{
-       struct map_context *ac;
-
-       ac = talloc_get_type(handle->private_data, struct map_context);
-
-       ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->remote_req);
-
-       ac->step = MAP_RENAME_REMOTE;
-
-       handle->state = LDB_ASYNC_INIT;
-       handle->status = LDB_SUCCESS;
-
-       return ldb_next_remote_request(ac->module, ac->remote_req);
-}
-
-/* Update the local 'IS_MAPPED' attribute. */
-int map_rename_do_fixup(struct ldb_handle *handle)
-{
-       struct map_context *ac;
-
-       ac = talloc_get_type(handle->private_data, struct map_context);
-
-       ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->down_req);
-
-       ac->step = MAP_RENAME_FIXUP;
-
-       handle->state = LDB_ASYNC_INIT;
-       handle->status = LDB_SUCCESS;
-
-       return ldb_next_request(ac->module, ac->down_req);
-}
-
-/* Rename the local record. */
-int map_rename_do_local(struct ldb_handle *handle)
+/* Delete the local record. */
+static int map_delete_do_local(struct map_context *ac)
 {
-       struct map_context *ac;
-
-       ac = talloc_get_type(handle->private_data, struct map_context);
+       struct ldb_request *local_req;
+       int ret;
 
        /* No local record, continue remotely */
        if (ac->local_dn == NULL) {
-               return map_rename_do_remote(handle);
+               /* Do the remote request. */
+               return ldb_next_remote_request(ac->module, ac->remote_req);
        }
 
-       ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->local_req);
-
-       ac->step = MAP_RENAME_LOCAL;
-
-       handle->state = LDB_ASYNC_INIT;
-       handle->status = LDB_SUCCESS;
-
-       return ldb_next_request(ac->module, ac->local_req);
+       /* Prepare the local operation */
+       ret = ldb_build_del_req(&local_req, ac->module->ldb, ac,
+                                  ac->req->op.del.dn,
+                                  ac->req->controls,
+                                  ac,
+                                  map_op_local_callback,
+                                  ac->req);
+       if (ret != LDB_SUCCESS) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+       return ldb_next_request(ac->module, local_req);
 }
 
+/*****************************************************************************
+ * RENAME operations
+*****************************************************************************/
+
 /* Rename a record. */
 int map_rename(struct ldb_module *module, struct ldb_request *req)
 {
-       struct ldb_handle *h;
+       struct ldb_request *search_req;
        struct map_context *ac;
+       int ret;
 
        /* Do not manipulate our control entries */
        if (ldb_dn_is_special(req->op.rename.olddn)) {
                return ldb_next_request(module, req);
        }
 
-       /* No mapping requested (perhaps no DN mapping specified), skip to next module */
+       /* No mapping requested (perhaps no DN mapping specified).
+        * Skip to next module */
        if ((!ldb_dn_check_local(module, req->op.rename.olddn)) &&
            (!ldb_dn_check_local(module, req->op.rename.newdn))) {
                return ldb_next_request(module, req);
@@ -658,66 +679,113 @@ int map_rename(struct ldb_module *module, struct ldb_request *req)
        }
 
        /* Prepare context and handle */
-       h = map_init_handle(req, module);
-       if (h == NULL) {
+       ac = map_init_context(module, req);
+       if (ac == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       ac = talloc_get_type(h->private_data, struct map_context);
 
-       /* Prepare the local operation */
-       ac->local_req = talloc(ac, struct ldb_request);
-       if (ac->local_req == NULL) {
-               goto oom;
+       /* Prepare the remote operation */
+       ret = ldb_build_rename_req(&ac->remote_req, module->ldb, ac,
+                                  ldb_dn_map_local(module, ac, req->op.rename.olddn),
+                                  ldb_dn_map_local(module, ac, req->op.rename.newdn),
+                                  req->controls,
+                                  ac, map_op_remote_callback,
+                                  req);
+       if (ret != LDB_SUCCESS) {
+               return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       *(ac->local_req) = *req;        /* copy the request */
-       ac->local_req->op.rename.olddn = req->op.rename.olddn;
-       ac->local_req->op.rename.newdn = req->op.rename.newdn;
+       /* No local db, just run the remote request */
+       if (!map_check_local_db(ac->module)) {
+               /* Do the remote request. */
+               return ldb_next_remote_request(ac->module, ac->remote_req);
+       }
 
-       ac->local_req->context = NULL;
-       ac->local_req->callback = NULL;
+       /* Prepare the search operation */
+       ret = map_search_self_req(&search_req, ac, req->op.rename.olddn);
+       if (ret != LDB_SUCCESS) {
+               map_oom(module);
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
 
-       /* Prepare the remote operation */
-       ac->remote_req = talloc(ac, struct ldb_request);
-       if (ac->remote_req == NULL) {
-               goto oom;
+       return ldb_next_request(module, search_req);
+}
+
+/* Rename the local record. */
+static int map_rename_do_local(struct map_context *ac)
+{
+       struct ldb_request *local_req;
+       int ret;
+
+       /* No local record, continue remotely */
+       if (ac->local_dn == NULL) {
+               /* Do the remote request. */
+               return ldb_next_remote_request(ac->module, ac->remote_req);
        }
 
-       *(ac->remote_req) = *req;       /* copy the request */
-       ac->remote_req->op.rename.olddn = ldb_dn_map_local(module, ac->remote_req, req->op.rename.olddn);
-       ac->remote_req->op.rename.newdn = ldb_dn_map_local(module, ac->remote_req, req->op.rename.newdn);
+       /* Prepare the local operation */
+       ret = ldb_build_rename_req(&local_req, ac->module->ldb, ac,
+                                  ac->req->op.rename.olddn,
+                                  ac->req->op.rename.newdn,
+                                  ac->req->controls,
+                                  ac,
+                                  map_rename_local_callback,
+                                  ac->req);
+       if (ret != LDB_SUCCESS) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
 
-       ac->remote_req->context = NULL;
-       ac->remote_req->callback = NULL;
+       return ldb_next_request(ac->module, local_req);
+}
 
-       /* No local db, just run the remote request */
-       if (!map_check_local_db(ac->module)) {
-               req->handle = h;        /* return our own handle to deal with this call */
-               return map_rename_do_remote(h);
+static int map_rename_local_callback(struct ldb_request *req,
+                                    struct ldb_reply *ares)
+{
+       struct map_context *ac;
+       int ret;
+
+       ac = talloc_get_type(req->context, struct map_context);
+
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
        }
 
-       /* Prepare the fixup operation */
-       /* TODO: use GUIDs here instead -- or skip it when GUIDs are used. */
-       ac->down_req = map_build_fixup_req(ac, req->op.rename.newdn, ac->remote_req->op.rename.newdn);
-       if (ac->down_req == NULL) {
-               goto failed;
+       if (ares->type != LDB_REPLY_DONE) {
+               ldb_set_errstring(req->handle->ldb, "Invalid reply type!");
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
        }
 
-       /* Prepare the search operation */
-       ac->search_req = map_search_self_req(ac, req->op.rename.olddn);
-       if (ac->search_req == NULL) {
-               goto failed;
+       /* proceed with next step */
+       ret = map_rename_do_fixup(ac);
+       if (ret != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
        }
 
-       req->handle = h;                /* return our own handle to deal with this call */
+       return LDB_SUCCESS;
+}
 
-       ac->step = MAP_SEARCH_SELF_RENAME;
+/* Update the local 'IS_MAPPED' attribute. */
+static int map_rename_do_fixup(struct map_context *ac)
+{
+       struct ldb_request *local_req;
 
-       return ldb_next_request(module, ac->search_req);
+       /* Prepare the fixup operation */
+       /* TODO: use GUIDs here instead -- or skip it when GUIDs are used. */
+       local_req = map_build_fixup_req(ac,
+                                       ac->req->op.rename.newdn,
+                                       ac->remote_req->op.rename.newdn,
+                                       ac,
+                                       map_op_local_callback);
+       if (local_req == NULL) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
 
-oom:
-       map_oom(module);
-failed:
-       talloc_free(h);
-       return LDB_ERR_OPERATIONS_ERROR;
+       return ldb_next_request(ac->module, local_req);
 }
index fbc097f31362ad0f3915f241c337562abd7da5b8..5f524a8be3c74109974319e6c2e7285f2758bd33 100644 (file)
@@ -4,6 +4,7 @@
    Copyright (C) Jelmer Vernooij 2005
    Copyright (C) Martin Kuehl <mkhl@samba.org> 2006
    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2006
+   Copyright (C) Simo Sorce <idra@samba.org> 2008
 
      ** NOTE! The following LGPL license applies to the ldb
      ** library. This does NOT imply that all of Samba is released
@@ -905,7 +906,11 @@ static int map_subtree_collect_remote(struct ldb_module *module, void *mem_ctx,
 
 /* Split subtrees that query attributes in the local partition from
  * those that query the remote partition. */
-static int ldb_parse_tree_partition(struct ldb_module *module, void *local_ctx, void *remote_ctx, struct ldb_parse_tree **local_tree, struct ldb_parse_tree **remote_tree, const struct ldb_parse_tree *tree)
+static int ldb_parse_tree_partition(struct ldb_module *module,
+                                       void *mem_ctx,
+                                       struct ldb_parse_tree **local_tree,
+                                       struct ldb_parse_tree **remote_tree,
+                                       const struct ldb_parse_tree *tree)
 {
        int ret;
 
@@ -918,13 +923,13 @@ static int ldb_parse_tree_partition(struct ldb_module *module, void *local_ctx,
        }
 
        /* Generate local tree */
-       ret = map_subtree_select_local(module, local_ctx, local_tree, tree);
+       ret = map_subtree_select_local(module, mem_ctx, local_tree, tree);
        if (ret) {
                return ret;
        }
 
        /* Generate remote tree */
-       ret = map_subtree_collect_remote(module, remote_ctx, remote_tree, tree);
+       ret = map_subtree_collect_remote(module, mem_ctx, remote_tree, tree);
        if (ret) {
                talloc_free(*local_tree);
                return ret;
@@ -1008,24 +1013,46 @@ oom:
 /* Outbound requests: search
  * ========================= */
 
-/* Pass a merged search result up the callback chain. */
-int map_up_callback(struct ldb_context *ldb, const struct ldb_request *req, struct ldb_reply *ares)
+static int map_remote_search_callback(struct ldb_request *req,
+                                       struct ldb_reply *ares);
+static int map_local_merge_callback(struct ldb_request *req,
+                                       struct ldb_reply *ares);
+static int map_search_local(struct map_context *ac);
+
+static int map_save_entry(struct map_context *ac, struct ldb_reply *ares)
 {
-       int i;
+       struct map_reply *mr;
 
-       /* No callback registered, stop */
-       if (req->callback == NULL) {
-               return LDB_SUCCESS;
+       mr = talloc_zero(ac, struct map_reply);
+       if (mr == NULL) {
+               map_oom(ac->module);
+               return LDB_ERR_OPERATIONS_ERROR;
        }
-
-       /* Only records need special treatment */
-       if (ares->type != LDB_REPLY_ENTRY) {
-               return req->callback(ldb, req->context, ares);
+       mr->remote = talloc_steal(mr, ares);
+       if (ac->r_current) {
+               ac->r_current->next = mr;
+       } else {
+               /* first entry */
+               ac->r_list = mr;
        }
+       ac->r_current = mr;
+
+       return LDB_SUCCESS;
+}
+
+/* Pass a merged search result up the callback chain. */
+int map_return_entry(struct map_context *ac, struct ldb_reply *ares)
+{
+       struct ldb_message_element *el;
+       const char * const *attrs;
+       int i;
 
        /* Merged result doesn't match original query, skip */
-       if (!ldb_match_msg(ldb, ares->message, req->op.search.tree, req->op.search.base, req->op.search.scope)) {
-               ldb_debug(ldb, LDB_DEBUG_TRACE, "ldb_map: "
+       if (!ldb_match_msg(ac->module->ldb, ares->message,
+                          ac->req->op.search.tree,
+                          ac->req->op.search.base,
+                          ac->req->op.search.scope)) {
+               ldb_debug(ac->module->ldb, LDB_DEBUG_TRACE, "ldb_map: "
                          "Skipping record '%s': "
                          "doesn't match original search\n",
                          ldb_dn_get_linearized(ares->message->dn));
@@ -1033,10 +1060,16 @@ int map_up_callback(struct ldb_context *ldb, const struct ldb_request *req, stru
        }
 
        /* Limit result to requested attrs */
-       if ((req->op.search.attrs) && (!ldb_attr_in_list(req->op.search.attrs, "*"))) {
-               for (i = 0; i < ares->message->num_elements; ) {
-                       struct ldb_message_element *el = &ares->message->elements[i];
-                       if (!ldb_attr_in_list(req->op.search.attrs, el->name)) {
+       if (ac->req->op.search.attrs &&
+           (! ldb_attr_in_list(ac->req->op.search.attrs, "*"))) {
+
+               attrs = ac->req->op.search.attrs;
+               i = 0;
+
+               while (i < ares->message->num_elements) {
+
+                       el = &ares->message->elements[i];
+                       if ( ! ldb_attr_in_list(attrs, el->name)) {
                                ldb_msg_remove_element(ares->message, el);
                        } else {
                                i++;
@@ -1044,129 +1077,16 @@ int map_up_callback(struct ldb_context *ldb, const struct ldb_request *req, stru
                }
        }
 
-       return req->callback(ldb, req->context, ares);
-}
-
-/* Merge the remote and local parts of a search result. */
-int map_local_merge_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares)
-{
-       struct map_search_context *sc;
-       int ret;
-
-       if (context == NULL || ares == NULL) {
-               ldb_set_errstring(ldb, talloc_asprintf(ldb, "ldb_map: "
-                                                      "NULL Context or Result in `map_local_merge_callback`"));
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       sc = talloc_get_type(context, struct map_search_context);
-
-       switch (ares->type) {
-       case LDB_REPLY_ENTRY:
-               /* We have already found a local record */
-               if (sc->local_res) {
-                       ldb_set_errstring(ldb, talloc_asprintf(ldb, "ldb_map: "
-                                                              "Too many results to base search for local entry"));
-                       talloc_free(ares);
-                       return LDB_ERR_OPERATIONS_ERROR;
-               }
-
-               /* Store local result */
-               sc->local_res = ares;
-
-               /* Merge remote into local message */
-               ret = ldb_msg_merge_local(sc->ac->module, ares->message, sc->remote_res->message);
-               if (ret) {
-                       talloc_free(ares);
-                       return LDB_ERR_OPERATIONS_ERROR;
-               }
-
-               return map_up_callback(ldb, sc->ac->orig_req, ares);
-
-       case LDB_REPLY_DONE:
-               /* No local record found, continue with remote record */
-               if (sc->local_res == NULL) {
-                       return map_up_callback(ldb, sc->ac->orig_req, sc->remote_res);
-               }
-               return LDB_SUCCESS;
-
-       default:
-               ldb_set_errstring(ldb, talloc_asprintf(ldb, "ldb_map: "
-                                                      "Unexpected result type in base search for local entry"));
-               talloc_free(ares);
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-}
-
-/* Search the local part of a remote search result. */
-int map_remote_search_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares)
-{
-       struct map_context *ac;
-       struct map_search_context *sc;
-       struct ldb_request *req;
-       int ret;
-
-       if (context == NULL || ares == NULL) {
-               ldb_set_errstring(ldb, talloc_asprintf(ldb, "ldb_map: "
-                                                      "NULL Context or Result in `map_remote_search_callback`"));
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       ac = talloc_get_type(context, struct map_context);
-
-       /* It's not a record, stop searching */
-       if (ares->type != LDB_REPLY_ENTRY) {
-               return map_up_callback(ldb, ac->orig_req, ares);
-       }
-
-       /* Map result record into a local message */
-       ret = map_reply_remote(ac, ares);
-       if (ret) {
-               talloc_free(ares);
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       /* There is no local db, stop searching */
-       if (!map_check_local_db(ac->module)) {
-               return map_up_callback(ldb, ac->orig_req, ares);
-       }
-
-       /* Prepare local search context */
-       sc = map_init_search_context(ac, ares);
-       if (sc == NULL) {
-               talloc_free(ares);
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       /* Prepare local search request */
-       /* TODO: use GUIDs here instead? */
-
-       ac->search_reqs = talloc_realloc(ac, ac->search_reqs, struct ldb_request *, ac->num_searches + 2);
-       if (ac->search_reqs == NULL) {
-               talloc_free(ares);
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       ac->search_reqs[ac->num_searches]
-               = req = map_search_base_req(ac, ares->message->dn, 
-                                           NULL, NULL, sc, map_local_merge_callback);
-       if (req == NULL) {
-               talloc_free(sc);
-               talloc_free(ares);
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-       ac->num_searches++;
-       ac->search_reqs[ac->num_searches] = NULL;
-
-       return ldb_next_request(ac->module, req);
+       return ldb_module_send_entry(ac->req, ares->message);
 }
 
 /* Search a record. */
 int map_search(struct ldb_module *module, struct ldb_request *req)
 {
-       struct ldb_handle *h;
+       struct ldb_parse_tree *remote_tree;
+       struct ldb_parse_tree *local_tree;
+       struct ldb_request *remote_req;
        struct map_context *ac;
-       struct ldb_parse_tree *local_tree, *remote_tree;
        int ret;
 
        const char *wildcard[] = { "*", NULL };
@@ -1176,8 +1096,9 @@ int map_search(struct ldb_module *module, struct ldb_request *req)
                return ldb_next_request(module, req);
 
        /* Do not manipulate our control entries */
-       if (ldb_dn_is_special(req->op.search.base))
+       if (ldb_dn_is_special(req->op.search.base)) {
                return ldb_next_request(module, req);
+       }
 
        /* No mapping requested, skip to next module */
        if ((req->op.search.base) && (!ldb_dn_check_local(module, req->op.search.base))) {
@@ -1188,32 +1109,10 @@ int map_search(struct ldb_module *module, struct ldb_request *req)
         *       targetting when there is no search base? */
 
        /* Prepare context and handle */
-       h = map_init_handle(req, module);
-       if (h == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-       ac = talloc_get_type(h->private_data, struct map_context);
-
-       ac->search_reqs = talloc_array(ac, struct ldb_request *, 2);
-       if (ac->search_reqs == NULL) {
-               talloc_free(h);
+       ac = map_init_context(module, req);
+       if (ac == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       ac->num_searches = 1;
-       ac->search_reqs[1] = NULL;
-
-       /* Prepare the remote operation */
-       ac->search_reqs[0] = talloc(ac, struct ldb_request);
-       if (ac->search_reqs[0] == NULL) {
-               goto oom;
-       }
-
-       *(ac->search_reqs[0]) = *req;   /* copy the request */
-
-       ac->search_reqs[0]->handle = h; /* return our own handle to deal with this call */
-
-       ac->search_reqs[0]->context = ac;
-       ac->search_reqs[0]->callback = map_remote_search_callback;
 
        /* It is easier to deal with the two different ways of
         * expressing the wildcard in the same codepath */
@@ -1226,17 +1125,15 @@ int map_search(struct ldb_module *module, struct ldb_request *req)
        ret = map_attrs_collect_and_partition(module, ac, 
                                              attrs, req->op.search.tree);
        if (ret) {
-               goto failed;
+               return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       ac->search_reqs[0]->op.search.attrs = ac->remote_attrs;
-
        /* Split local from remote tree */
-       ret = ldb_parse_tree_partition(module, ac, ac->search_reqs[0], 
-                                      &local_tree, &remote_tree, 
+       ret = ldb_parse_tree_partition(module, ac,
+                                      &local_tree, &remote_tree,
                                       req->op.search.tree);
        if (ret) {
-               goto failed;
+               return LDB_ERR_OPERATIONS_ERROR;
        }
 
        if (((local_tree != NULL) && (remote_tree != NULL)) &&
@@ -1251,7 +1148,7 @@ int map_search(struct ldb_module *module, struct ldb_request *req)
                local_tree = talloc_zero(ac, struct ldb_parse_tree);
                if (local_tree == NULL) {
                        map_oom(ac->module);
-                       goto failed;
+                       return LDB_ERR_OPERATIONS_ERROR;
                }
 
                local_tree->operation = LDB_OP_PRESENT;
@@ -1259,31 +1156,209 @@ int map_search(struct ldb_module *module, struct ldb_request *req)
        }
        if (remote_tree == NULL) {
                /* Construct default remote parse tree */
-               remote_tree = ldb_parse_tree(ac->search_reqs[0], NULL);
+               remote_tree = ldb_parse_tree(ac, NULL);
                if (remote_tree == NULL) {
-                       goto failed;
+                       return LDB_ERR_OPERATIONS_ERROR;
                }
        }
 
        ac->local_tree = local_tree;
-       ac->search_reqs[0]->op.search.tree = remote_tree;
 
-       ldb_set_timeout_from_prev_req(module->ldb, req, ac->search_reqs[0]);
+       /* Prepare the remote operation */
+       ret = ldb_build_search_req_ex(&remote_req, module->ldb, ac,
+                                     req->op.search.base,
+                                     req->op.search.scope,
+                                     remote_tree,
+                                     ac->remote_attrs,
+                                     req->controls,
+                                     ac, map_remote_search_callback,
+                                     req);
+       if (ret != LDB_SUCCESS) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
 
-       h->state = LDB_ASYNC_INIT;
-       h->status = LDB_SUCCESS;
+       return ldb_next_remote_request(module, remote_req);
+}
+
+/* Now, search the local part of a remote search result. */
+static int map_remote_search_callback(struct ldb_request *req,
+                                       struct ldb_reply *ares)
+{
+       struct map_context *ac;
+       int ret;
 
-       ac->step = MAP_SEARCH_REMOTE;
+       ac = talloc_get_type(req->context, struct map_context);
 
-       ret = ldb_next_remote_request(module, ac->search_reqs[0]);
-       if (ret == LDB_SUCCESS) {
-               req->handle = h;
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
        }
-       return ret;
 
-oom:
-       map_oom(module);
-failed:
-       talloc_free(h);
-       return LDB_ERR_OPERATIONS_ERROR;
+       switch (ares->type) {
+       case LDB_REPLY_REFERRAL:
+
+               /* ignore referrals */
+               talloc_free(ares);
+               return LDB_SUCCESS;
+
+       case LDB_REPLY_ENTRY:
+
+               /* Map result record into a local message */
+               ret = map_reply_remote(ac, ares);
+               if (ret) {
+                       talloc_free(ares);
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
+               }
+
+               /* if we have no local db, then we can just return the reply to
+                * the upper layer, otherwise we must save it and process it
+                * when all replies ahve been gathered */
+               if ( ! map_check_local_db(ac->module)) {
+                       ret = map_return_entry(ac, ares);
+               } else {
+                       ret = map_save_entry(ac,ares);
+               }
+
+               if (ret != LDB_SUCCESS) {
+                       talloc_free(ares);
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
+               }
+               break;
+
+       case LDB_REPLY_DONE:
+
+               if ( ! map_check_local_db(ac->module)) {
+                       return ldb_module_done(ac->req, ares->controls,
+                                               ares->response, LDB_SUCCESS);
+               }
+
+               talloc_free(ares);
+
+               /* reset the pointer to the start of the list */
+               ac->r_current = ac->r_list;
+
+               /* no entry just return */
+               if (ac->r_current == NULL) {
+                       return ldb_module_done(ac->req, ares->controls,
+                                               ares->response, LDB_SUCCESS);
+               }
+
+               ret = map_search_local(ac);
+               if (ret != LDB_SUCCESS) {
+                       return ldb_module_done(ac->req, NULL, NULL, ret);
+               }
+       }
+
+       return LDB_SUCCESS;
+}
+
+static int map_search_local(struct map_context *ac)
+{
+       struct ldb_request *search_req;
+
+       if (ac->r_current == NULL || ac->r_current->remote == NULL) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       /* Prepare local search request */
+       /* TODO: use GUIDs here instead? */
+       search_req = map_search_base_req(ac,
+                                        ac->r_current->remote->message->dn,
+                                        NULL, NULL,
+                                        ac, map_local_merge_callback);
+       if (search_req == NULL) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       return ldb_next_request(ac->module, search_req);
+}
+
+/* Merge the remote and local parts of a search result. */
+int map_local_merge_callback(struct ldb_request *req, struct ldb_reply *ares)
+{
+       struct map_context *ac;
+       int ret;
+
+       ac = talloc_get_type(req->context, struct map_context);
+
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
+
+       switch (ares->type) {
+       case LDB_REPLY_ENTRY:
+               /* We have already found a local record */
+               if (ac->r_current->local) {
+                       talloc_free(ares);
+                       ldb_set_errstring(ac->module->ldb, "ldb_map: Too many results!");
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
+               }
+
+               /* Store local result */
+               ac->r_current->local = talloc_steal(ac->r_current, ares);
+
+               break;
+
+       case LDB_REPLY_REFERRAL:
+               /* ignore referrals */
+               talloc_free(ares);
+               break;
+
+       case LDB_REPLY_DONE:
+               talloc_free(ares);
+
+               /* No local record found, map and send remote record */
+               if (ac->r_current->local != NULL) {
+                       /* Merge remote into local message */
+                       ret = ldb_msg_merge_local(ac->module,
+                                                 ac->r_current->local->message,
+                                                 ac->r_current->remote->message);
+                       if (ret == LDB_SUCCESS) {
+                               ret = map_return_entry(ac, ac->r_current->local);
+                       }
+                       if (ret != LDB_SUCCESS) {
+                               return ldb_module_done(ac->req, NULL, NULL,
+                                                       LDB_ERR_OPERATIONS_ERROR);
+                       }
+               } else {
+                       ret = map_return_entry(ac, ac->r_current->remote);
+                       if (ret != LDB_SUCCESS) {
+                               return ldb_module_done(ac->req,
+                                                       NULL, NULL, ret);
+                       }
+               }
+
+               if (ac->r_current->next != NULL) {
+                       ac->r_current = ac->r_current->next;
+                       if (ac->r_current->remote->type == LDB_REPLY_ENTRY) {
+                               ret = map_search_local(ac);
+                               if (ret != LDB_SUCCESS) {
+                                       return ldb_module_done(ac->req,
+                                                              NULL, NULL, ret);
+                               }
+                               break;
+                       }
+               }
+
+               /* ok we are done with all search, finally it is time to
+                * finish operations for this module */
+               return ldb_module_done(ac->req,
+                                       ac->r_current->remote->controls,
+                                       ac->r_current->remote->response,
+                                       ac->r_current->remote->error);
+       }
+
+       return LDB_SUCCESS;
 }
index 58a9f2704ef8eafd65457cb339304e1b57637cff..5522125344e84394e44bc67b2d8116443ef3b172 100644 (file)
@@ -3,7 +3,7 @@
 #define map_oom(module) ldb_set_errstring(module->ldb, talloc_asprintf(module, "Out of Memory"));
 
 /* The type of search callback functions */
-typedef int (*ldb_search_callback)(struct ldb_context *, void *, struct ldb_reply *);
+typedef int (*ldb_map_callback_t)(struct ldb_request *, struct ldb_reply *);
 
 /* The special DN from which the local and remote base DNs are fetched */
 #define MAP_DN_NAME    "@MAP"
@@ -13,25 +13,17 @@ typedef int (*ldb_search_callback)(struct ldb_context *, void *, struct ldb_repl
 /* Private data structures
  * ======================= */
 
+struct map_reply {
+       struct map_reply *next;
+       struct ldb_reply *remote;
+       struct ldb_reply *local;
+};
+
 /* Context data for mapped requests */
 struct map_context {
-       enum map_step {
-               MAP_SEARCH_REMOTE,
-               MAP_ADD_REMOTE,
-               MAP_ADD_LOCAL,
-               MAP_SEARCH_SELF_MODIFY,
-               MAP_MODIFY_REMOTE,
-               MAP_MODIFY_LOCAL,
-               MAP_SEARCH_SELF_DELETE,
-               MAP_DELETE_REMOTE,
-               MAP_DELETE_LOCAL,
-               MAP_SEARCH_SELF_RENAME,
-               MAP_RENAME_REMOTE,
-               MAP_RENAME_FIXUP,
-               MAP_RENAME_LOCAL
-       } step;
 
        struct ldb_module *module;
+       struct ldb_request *req;
 
        struct ldb_dn *local_dn;
        const struct ldb_parse_tree *local_tree;
@@ -39,32 +31,20 @@ struct map_context {
        const char * const *remote_attrs;
        const char * const *all_attrs;
 
-       struct ldb_request *orig_req;
-       struct ldb_request *local_req;
+       struct ldb_message *local_msg;
        struct ldb_request *remote_req;
-       struct ldb_request *down_req;
-       struct ldb_request *search_req;
-
-       /* for search, we may have a lot of contexts */
-       int num_searches;
-       struct ldb_request **search_reqs;
-};
 
-/* Context data for mapped search requests */
-struct map_search_context {
-       struct map_context *ac;
-       struct ldb_reply *local_res;
-       struct ldb_reply *remote_res;
+       struct map_reply *r_list;
+       struct map_reply *r_current;
 };
 
-
 /* Common operations
  * ================= */
 
 /* The following definitions come from lib/ldb/modules/ldb_map.c */
 const struct ldb_map_context *map_get_context(struct ldb_module *module);
-struct map_search_context *map_init_search_context(struct map_context *ac, struct ldb_reply *ares);
-struct ldb_handle *map_init_handle(struct ldb_request *req, struct ldb_module *module);
+struct map_context *map_init_context(struct ldb_module *module,
+                                       struct ldb_request *req);
 
 int ldb_next_remote_request(struct ldb_module *module, struct ldb_request *request);
 
@@ -86,25 +66,23 @@ struct ldb_dn *ldb_dn_map_local(struct ldb_module *module, void *mem_ctx, struct
 struct ldb_dn *ldb_dn_map_remote(struct ldb_module *module, void *mem_ctx, struct ldb_dn *dn);
 struct ldb_dn *ldb_dn_map_rebase_remote(struct ldb_module *module, void *mem_ctx, struct ldb_dn *dn);
 
-struct ldb_request *map_search_base_req(struct map_context *ac, struct ldb_dn *dn, const char * const *attrs, const struct ldb_parse_tree *tree, void *context, ldb_search_callback callback);
-struct ldb_request *map_search_self_req(struct map_context *ac, struct ldb_dn *dn);
-struct ldb_request *map_build_fixup_req(struct map_context *ac, struct ldb_dn *olddn, struct ldb_dn *newdn);
-
-int map_subtree_collect_remote_simple(struct ldb_module *module, void *mem_ctx, struct ldb_parse_tree **new, const struct ldb_parse_tree *tree, const struct ldb_map_attribute *map);
-
-/* LDB Requests
- * ============ */
-
-/* The following definitions come from lib/ldb/modules/ldb_map_inbound.c */
-int map_add_do_remote(struct ldb_handle *handle);
-int map_add_do_local(struct ldb_handle *handle);
-
-int map_modify_do_remote(struct ldb_handle *handle);
-int map_modify_do_local(struct ldb_handle *handle);
-
-int map_delete_do_remote(struct ldb_handle *handle);
-int map_delete_do_local(struct ldb_handle *handle);
-
-int map_rename_do_remote(struct ldb_handle *handle);
-int map_rename_do_fixup(struct ldb_handle *handle);
-int map_rename_do_local(struct ldb_handle *handle);
+struct ldb_request *map_search_base_req(struct map_context *ac,
+                                       struct ldb_dn *dn,
+                                       const char * const *attrs,
+                                       const struct ldb_parse_tree *tree,
+                                       void *context,
+                                       ldb_map_callback_t callback);
+struct ldb_request *map_build_fixup_req(struct map_context *ac,
+                                       struct ldb_dn *olddn,
+                                       struct ldb_dn *newdn,
+                                       void *context,
+                                       ldb_map_callback_t callback);
+int map_subtree_collect_remote_simple(struct ldb_module *module, void *mem_ctx,
+                                       struct ldb_parse_tree **new,
+                                       const struct ldb_parse_tree *tree,
+                                       const struct ldb_map_attribute *map);
+int map_return_fatal_error(struct ldb_request *req,
+                          struct ldb_reply *ares);
+int map_return_normal_error(struct ldb_request *req,
+                           struct ldb_reply *ares,
+                           int error);
index a0e63c8da1fe817441a15977683f0bfbbeb19cc0..be99c29d1e6cc948cdd37df5d4bcca51b3bd2a2e 100644 (file)
@@ -44,51 +44,14 @@ struct lsqlite3_private {
 
 struct lsql_context {
        struct ldb_module *module;
+       struct ldb_request *req;
 
        /* search stuff */
        long long current_eid;
        const char * const * attrs;
        struct ldb_reply *ares;
-
-       /* async stuff */
-       void *context;
-       int (*callback)(struct ldb_context *, void *, struct ldb_reply *);
 };
 
-static struct ldb_handle *init_handle(struct lsqlite3_private *lsqlite3,
-                                       struct ldb_module *module,
-                                       struct ldb_request *req)
-{
-       struct lsql_context *ac;
-       struct ldb_handle *h;
-
-       h = talloc_zero(lsqlite3, struct ldb_handle);
-       if (h == NULL) {
-               ldb_set_errstring(module->ldb, "Out of Memory");
-               return NULL;
-       }
-
-       h->module = module;
-
-       ac = talloc(h, struct lsql_context);
-       if (ac == NULL) {
-               ldb_set_errstring(module->ldb, "Out of Memory");
-               talloc_free(h);
-               return NULL;
-       }
-
-       h->private_data = (void *)ac;
-
-       h->state = LDB_ASYNC_INIT;
-       h->status = LDB_SUCCESS;
-
-       ac->module = module;
-       ac->context = req->context;
-       ac->callback = req->callback;
-
-       return h;
-}
-
 /*
  * Macros used throughout
  */
@@ -835,11 +798,6 @@ int lsql_search(struct ldb_module *module, struct ldb_request *req)
        char *query = NULL;
         int ret;
 
-       req->handle = init_handle(lsqlite3, module, req);
-       if (req->handle == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
        lsql_ac = talloc_get_type(req->handle->private_data, struct lsql_context);
 
        if ((( ! ldb_dn_is_valid(req->op.search.base)) || ldb_dn_is_null(req->op.search.base)) &&
@@ -1013,10 +971,6 @@ static int lsql_add(struct ldb_module *module, struct ldb_request *req)
        int i;
        int ret = LDB_SUCCESS;
 
-       req->handle = init_handle(lsqlite3, module, req);
-       if (req->handle == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
        lsql_ac = talloc_get_type(req->handle->private_data, struct lsql_context);
        req->handle->state = LDB_ASYNC_DONE;
        req->handle->status = LDB_SUCCESS;
@@ -1143,10 +1097,6 @@ static int lsql_modify(struct ldb_module *module, struct ldb_request *req)
        int i;
        int ret = LDB_SUCCESS;
 
-       req->handle = init_handle(lsqlite3, module, req);
-       if (req->handle == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
        lsql_ac = talloc_get_type(req->handle->private_data, struct lsql_context);
        req->handle->state = LDB_ASYNC_DONE;
        req->handle->status = LDB_SUCCESS;
@@ -1329,10 +1279,6 @@ static int lsql_delete(struct ldb_module *module, struct ldb_request *req)
        int ret = LDB_SUCCESS;
 
 
-       req->handle = init_handle(lsqlite3, module, req);
-       if (req->handle == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
        lsql_ac = talloc_get_type(req->handle->private_data, struct lsql_context);
        req->handle->state = LDB_ASYNC_DONE;
        req->handle->status = LDB_SUCCESS;
@@ -1382,10 +1328,6 @@ static int lsql_rename(struct ldb_module *module, struct ldb_request *req)
        char *query;
        int ret = LDB_SUCCESS;
 
-       req->handle = init_handle(lsqlite3, module, req);
-       if (req->handle == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
        lsql_ac = talloc_get_type(req->handle->private_data, struct lsql_context);
        req->handle->state = LDB_ASYNC_DONE;
        req->handle->status = LDB_SUCCESS;
@@ -1501,9 +1443,61 @@ static int lsql_request(struct ldb_module *module, struct ldb_request *req)
        return LDB_ERR_OPERATIONS_ERROR;
 }
 
-static int lsql_wait(struct ldb_handle *handle, enum ldb_wait_type type)
+static int lsql_run_request(struct ldb_module *module, struct ldb_request *req)
+{
+       switch (req->operation) {
+       case LDB_SEARCH:
+               return lsql_search(module, req);
+               break;
+       case LDB_ADD:
+               return lsql_add(module, req);
+               break;
+       case LDB_MODIFY:
+               return lsql_modify(module, req);
+               break;
+       case LDB_DELETE:
+               return lsql_delete(module, req);
+               break;
+       case LDB_RENAME:
+               return lsql_rename(module, req);
+               break;
+/* TODO:
+       case LDB_SEQUENCE_NUMBER:
+               return lsql_sequence_number(module, req);
+               break;
+ */
+       default:
+               return lsql_request(module, req);
+               break;
+       }
+
+       return LDB_ERR_OPERATIONS_ERROR;
+}
+
+static int lsql_handle_request(struct ldb_module *module, struct ldb_request *req)
 {
-       return handle->status;
+       struct lsql_context *ac;
+
+       if (check_critical_controls(req->controls)) {
+               return LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION;
+       }
+
+       ac = talloc_zero(req, struct lsql_context);
+       if (ac == NULL) {
+               ldb_set_errstring(module->ldb, "Out of Memory");
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       ac->module = module;
+       ac->req = req;
+
+       req->handle = ldb_handle_new(req, lsql_run_request, ac);
+       if (req->handle == NULL) {
+               talloc_free(ac);
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       return LDB_SUCCESS;
 }
 
 /*
@@ -1511,16 +1505,16 @@ static int lsql_wait(struct ldb_handle *handle, enum ldb_wait_type type)
  */
 static const struct ldb_module_ops lsqlite3_ops = {
        .name              = "sqlite",
-       .search            = lsql_search,
-       .add               = lsql_add,
-        .modify            = lsql_modify,
-        .del               = lsql_delete,
-        .rename            = lsql_rename,
-       .request           = lsql_request,
+       .search            = lsql_handle_request,
+       .add               = lsql_handle_request,
+        .modify            = lsql_handle_request,
+        .del               = lsql_handle_request,
+        .rename            = lsql_handle_request,
+       .request           = lsql_handle_request,
        .start_transaction = lsql_start_trans,
        .end_transaction   = lsql_end_trans,
        .del_transaction   = lsql_del_trans,
-       .wait              = lsql_wait,
+       /* TODO: .sequence_number   = lsql_handle_request */
 };
 
 /*
index 269305a4680c90c94ad4dc625486ad3b5bcaffcc..65711d9f4b90cb68568a0e85e1a4e367cccff743 100644 (file)
@@ -667,74 +667,58 @@ static int ltdb_index_dn(struct ldb_module *module,
   extracting just the given attributes
 */
 static int ltdb_index_filter(const struct dn_list *dn_list, 
-                            struct ldb_handle *handle)
+                            struct ltdb_context *ac)
 {
-       struct ltdb_context *ac = talloc_get_type(handle->private_data, struct ltdb_context);
-       struct ldb_reply *ares = NULL;
+       struct ldb_message *msg;
        unsigned int i;
 
        for (i = 0; i < dn_list->count; i++) {
                struct ldb_dn *dn;
                int ret;
 
-               ares = talloc_zero(ac, struct ldb_reply);
-               if (!ares) {
-                       handle->status = LDB_ERR_OPERATIONS_ERROR;
-                       handle->state = LDB_ASYNC_DONE;
-                       return LDB_ERR_OPERATIONS_ERROR;
-               }
-
-               ares->message = ldb_msg_new(ares);
-               if (!ares->message) {
-                       handle->status = LDB_ERR_OPERATIONS_ERROR;
-                       handle->state = LDB_ASYNC_DONE;
-                       talloc_free(ares);
+               msg = ldb_msg_new(ac);
+               if (!msg) {
                        return LDB_ERR_OPERATIONS_ERROR;
                }
 
-
-               dn = ldb_dn_new(ares->message, ac->module->ldb, dn_list->dn[i]);
+               dn = ldb_dn_new(msg, ac->module->ldb, dn_list->dn[i]);
                if (dn == NULL) {
-                       talloc_free(ares);
+                       talloc_free(msg);
                        return LDB_ERR_OPERATIONS_ERROR;
                }
 
-               ret = ltdb_search_dn1(ac->module, dn, ares->message);
+               ret = ltdb_search_dn1(ac->module, dn, msg);
                talloc_free(dn);
                if (ret == LDB_ERR_NO_SUCH_OBJECT) {
                        /* the record has disappeared? yes, this can happen */
-                       talloc_free(ares);
+                       talloc_free(msg);
                        continue;
                }
 
                if (ret != LDB_SUCCESS && ret != LDB_ERR_NO_SUCH_OBJECT) {
                        /* an internal error */
-                       talloc_free(ares);
+                       talloc_free(msg);
                        return LDB_ERR_OPERATIONS_ERROR;
                }
 
-               if (!ldb_match_msg(ac->module->ldb, ares->message, ac->tree, ac->base, ac->scope)) {
-                       talloc_free(ares);
+               if (!ldb_match_msg(ac->module->ldb, msg,
+                                  ac->tree, ac->base, ac->scope)) {
+                       talloc_free(msg);
                        continue;
                }
 
                /* filter the attributes that the user wants */
-               ret = ltdb_filter_attrs(ares->message, ac->attrs);
+               ret = ltdb_filter_attrs(msg, ac->attrs);
 
                if (ret == -1) {
-                       handle->status = LDB_ERR_OPERATIONS_ERROR;
-                       handle->state = LDB_ASYNC_DONE;
-                       talloc_free(ares);
+                       talloc_free(msg);
                        return LDB_ERR_OPERATIONS_ERROR;
                }
 
-               ares->type = LDB_REPLY_ENTRY;
-               handle->state = LDB_ASYNC_PENDING;
-               handle->status = ac->callback(ac->module->ldb, ac->context, ares);
-
-               if (handle->status != LDB_SUCCESS) {
-                       handle->state = LDB_ASYNC_DONE;
-                       return handle->status;
+               ret = ldb_module_send_entry(ac->req, msg);
+               if (ret != LDB_SUCCESS) {
+                       ac->callback_failed = true;
+                       return ret;
                }
        }
 
@@ -746,9 +730,8 @@ static int ltdb_index_filter(const struct dn_list *dn_list,
   returns -1 if an indexed search is not possible, in which
   case the caller should call ltdb_search_full() 
 */
-int ltdb_search_indexed(struct ldb_handle *handle)
+int ltdb_search_indexed(struct ltdb_context *ac)
 {
-       struct ltdb_context *ac = talloc_get_type(handle->private_data, struct ltdb_context);
        struct ltdb_private *ltdb = talloc_get_type(ac->module->private_data, struct ltdb_private);
        struct dn_list *dn_list;
        int ret, idxattr, idxone;
@@ -773,7 +756,7 @@ int ltdb_search_indexed(struct ldb_handle *handle)
 
        ret = LDB_ERR_OPERATIONS_ERROR;
 
-       dn_list = talloc_zero(handle, struct dn_list);
+       dn_list = talloc_zero(ac, struct dn_list);
        if (dn_list == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
@@ -810,9 +793,7 @@ int ltdb_search_indexed(struct ldb_handle *handle)
        if (ret == LDB_SUCCESS) {
                /* we've got a candidate list - now filter by the full tree
                   and extract the needed attributes */
-               ret = ltdb_index_filter(dn_list, handle);
-               handle->status = ret;
-               handle->state = LDB_ASYNC_DONE;
+               ret = ltdb_index_filter(dn_list, ac);
        }
 
        talloc_free(dn_list);
index da899c361edac6da084545fbbb3885daccce30f9..a220b4a6288c7f17ef4ce57ca4d36681e499a811 100644 (file)
@@ -395,71 +395,57 @@ int ltdb_filter_attrs(struct ldb_message *msg, const char * const *attrs)
  */
 static int search_func(struct tdb_context *tdb, TDB_DATA key, TDB_DATA data, void *state)
 {
-       struct ldb_handle *handle = talloc_get_type(state, struct ldb_handle);
-       struct ltdb_context *ac = talloc_get_type(handle->private_data, struct ltdb_context);
-       struct ldb_reply *ares = NULL;
+       struct ltdb_context *ac;
+       struct ldb_message *msg;
        int ret;
 
+       ac = talloc_get_type(state, struct ltdb_context);
+
        if (key.dsize < 4 || 
            strncmp((char *)key.dptr, "DN=", 3) != 0) {
                return 0;
        }
 
-       ares = talloc_zero(ac, struct ldb_reply);
-       if (!ares) {
-               handle->status = LDB_ERR_OPERATIONS_ERROR;
-               handle->state = LDB_ASYNC_DONE;
-               return -1;
-       }
-
-       ares->message = ldb_msg_new(ares);
-       if (!ares->message) {
-               handle->status = LDB_ERR_OPERATIONS_ERROR;
-               handle->state = LDB_ASYNC_DONE;
-               talloc_free(ares);
+       msg = ldb_msg_new(ac);
+       if (!msg) {
                return -1;
        }
 
        /* unpack the record */
-       ret = ltdb_unpack_data(ac->module, &data, ares->message);
+       ret = ltdb_unpack_data(ac->module, &data, msg);
        if (ret == -1) {
-               talloc_free(ares);
+               talloc_free(msg);
                return -1;
        }
 
-       if (!ares->message->dn) {
-               ares->message->dn = ldb_dn_new(ares->message, ac->module->ldb, (char *)key.dptr + 3);
-               if (ares->message->dn == NULL) {
-                       handle->status = LDB_ERR_OPERATIONS_ERROR;
-                       handle->state = LDB_ASYNC_DONE;
-                       talloc_free(ares);
+       if (!msg->dn) {
+               msg->dn = ldb_dn_new(msg, ac->module->ldb,
+                                    (char *)key.dptr + 3);
+               if (msg->dn == NULL) {
+                       talloc_free(msg);
                        return -1;
                }
        }
 
        /* see if it matches the given expression */
-       if (!ldb_match_msg(ac->module->ldb, ares->message, ac->tree, 
-                              ac->base, ac->scope)) {
-               talloc_free(ares);
+       if (!ldb_match_msg(ac->module->ldb, msg,
+                          ac->tree, ac->base, ac->scope)) {
+               talloc_free(msg);
                return 0;
        }
 
        /* filter the attributes that the user wants */
-       ret = ltdb_filter_attrs(ares->message, ac->attrs);
+       ret = ltdb_filter_attrs(msg, ac->attrs);
 
        if (ret == -1) {
-               handle->status = LDB_ERR_OPERATIONS_ERROR;
-               handle->state = LDB_ASYNC_DONE;
-               talloc_free(ares);
+               talloc_free(msg);
                return -1;
        }
 
-       ares->type = LDB_REPLY_ENTRY;
-        handle->state = LDB_ASYNC_PENDING;
-       handle->status = ac->callback(ac->module->ldb, ac->context, ares);
-
-       if (handle->status != LDB_SUCCESS) {
-               /* don't try to free ares here, the callback is in charge of that */
+       ret = ldb_module_send_entry(ac->req, msg);
+       if (ret != LDB_SUCCESS) {
+               ac->callback_failed = true;
+               /* the callback failed, abort the operation */
                return -1;
        }       
 
@@ -471,23 +457,21 @@ static int search_func(struct tdb_context *tdb, TDB_DATA key, TDB_DATA data, voi
   search the database with a LDAP-like expression.
   this is the "full search" non-indexed variant
 */
-static int ltdb_search_full(struct ldb_handle *handle)
+static int ltdb_search_full(struct ltdb_context *ctx)
 {
-       struct ltdb_context *ac = talloc_get_type(handle->private_data, struct ltdb_context);
-       struct ltdb_private *ltdb = talloc_get_type(ac->module->private_data, struct ltdb_private);
+       struct ltdb_private *ltdb = talloc_get_type(ctx->module->private_data, struct ltdb_private);
        int ret;
 
        if (ltdb->in_transaction != 0) {
-               ret = tdb_traverse(ltdb->tdb, search_func, handle);
+               ret = tdb_traverse(ltdb->tdb, search_func, ctx);
        } else {
-               ret = tdb_traverse_read(ltdb->tdb, search_func, handle);
+               ret = tdb_traverse_read(ltdb->tdb, search_func, ctx);
        }
 
        if (ret == -1) {
-               handle->status = LDB_ERR_OPERATIONS_ERROR;
+               return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       handle->state = LDB_ASYNC_DONE;
        return LDB_SUCCESS;
 }
 
@@ -495,13 +479,15 @@ static int ltdb_search_full(struct ldb_handle *handle)
   search the database with a LDAP-like expression.
   choses a search method
 */
-int ltdb_search(struct ldb_module *module, struct ldb_request *req)
+int ltdb_search(struct ltdb_context *ctx)
 {
+       struct ldb_module *module = ctx->module;
+       struct ldb_request *req = ctx->req;
        struct ltdb_private *ltdb = talloc_get_type(module->private_data, struct ltdb_private);
-       struct ltdb_context *ltdb_ac;
-       struct ldb_reply *ares;
        int ret;
 
+       req->handle->state = LDB_ASYNC_PENDING;
+
        if (ltdb_lock_read(module) != 0) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
@@ -516,12 +502,6 @@ int ltdb_search(struct ldb_module *module, struct ldb_request *req)
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       req->handle = init_ltdb_handle(ltdb, module, req);
-       if (req->handle == NULL) {
-               ltdb_unlock_read(module);
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
        if ((req->op.search.base == NULL) || (ldb_dn_is_null(req->op.search.base) == true)) {
 
                /* Check what we should do with a NULL dn */
@@ -564,53 +544,32 @@ int ltdb_search(struct ldb_module *module, struct ldb_request *req)
                ret = LDB_SUCCESS;
        }
 
-       ltdb_ac = talloc_get_type(req->handle->private_data, struct ltdb_context);
-
-       ltdb_ac->tree = req->op.search.tree;
-       ltdb_ac->scope = req->op.search.scope;
-       ltdb_ac->base = req->op.search.base;
-       ltdb_ac->attrs = req->op.search.attrs;
-
+       ctx->tree = req->op.search.tree;
+       ctx->scope = req->op.search.scope;
+       ctx->base = req->op.search.base;
+       ctx->attrs = req->op.search.attrs;
 
        if (ret == LDB_SUCCESS) {
-               ret = ltdb_search_indexed(req->handle);
+               ret = ltdb_search_indexed(ctx);
                if (ret == LDB_ERR_NO_SUCH_OBJECT) {
                        /* Not in the index, therefore OK! */
                        ret = LDB_SUCCESS;
                        
-               } else if (ret == LDB_ERR_OPERATIONS_ERROR) {
+               }
+               /* Check if we got just a normal error.
+                * In that case proceed to a full search unless we got a
+                * callback error */
+               if ( ! ctx->callback_failed && ret != LDB_SUCCESS) {
                        /* Not indexed, so we need to do a full scan */
-                       ret = ltdb_search_full(req->handle);
+                       ret = ltdb_search_full(ctx);
                        if (ret != LDB_SUCCESS) {
                                ldb_set_errstring(module->ldb, "Indexed and full searches both failed!\n");
                        }
                }
        }
 
-       if (ret != LDB_SUCCESS) {
-               req->handle->state = LDB_ASYNC_DONE;
-               req->handle->status = ret;
-       }
-
-       /* Finally send an LDB_REPLY_DONE packet when searching is finished */
-
-       ares = talloc_zero(req, struct ldb_reply);
-       if (!ares) {
-               ltdb_unlock_read(module);
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       req->handle->state = LDB_ASYNC_DONE;
-
-       if (ret == LDB_SUCCESS) {
-               ares->type = LDB_REPLY_DONE;
-               
-               ret = req->callback(module->ldb, req->context, ares);
-               req->handle->status = ret;
-       }
-
        ltdb_unlock_read(module);
 
-       return LDB_SUCCESS;
+       return ret;
 }
 
index 01d570c89ad7f954ab218055adb6dd753acbb0cd..0087f6c44d40affe2c7f3c00b19d3358a508b65f 100644 (file)
@@ -3,7 +3,7 @@
 
    Copyright (C) Andrew Tridgell  2004
    Copyright (C) Stefan Metzmacher  2004
-   Copyright (C) Simo Sorce       2006
+   Copyright (C) Simo Sorce       2006-2008
 
 
      ** NOTE! The following LGPL license applies to the ldb
  *  - description: make the module use asyncronous calls
  *    date: Feb 2006
  *    Author: Simo Sorce
+ *
+ *  - description: make it possible to use event contexts
+ *    date: Jan 2008
+ *    Author: Simo Sorce
  */
 
 #include "ldb_includes.h"
@@ -76,40 +80,6 @@ static int ltdb_err_map(enum TDB_ERROR tdb_code)
 }
 
 
-struct ldb_handle *init_ltdb_handle(struct ltdb_private *ltdb,
-                                   struct ldb_module *module,
-                                   struct ldb_request *req)
-{
-       struct ltdb_context *ac;
-       struct ldb_handle *h;
-
-       h = talloc_zero(req, struct ldb_handle);
-       if (h == NULL) {
-               ldb_set_errstring(module->ldb, "Out of Memory");
-               return NULL;
-       }
-
-       h->module = module;
-
-       ac = talloc_zero(h, struct ltdb_context);
-       if (ac == NULL) {
-               ldb_set_errstring(module->ldb, "Out of Memory");
-               talloc_free(h);
-               return NULL;
-       }
-
-       h->private_data = (void *)ac;
-
-       h->state = LDB_ASYNC_INIT;
-       h->status = LDB_SUCCESS;
-
-       ac->module = module;
-       ac->context = req->context;
-       ac->callback = req->callback;
-
-       return h;
-}
-
 /*
   form a TDB_DATA for a record key
   caller frees
@@ -296,36 +266,20 @@ static int ltdb_add_internal(struct ldb_module *module,
 /*
   add a record to the database
 */
-static int ltdb_add(struct ldb_module *module, struct ldb_request *req)
+static int ltdb_add(struct ltdb_context *ctx)
 {
-       struct ltdb_private *ltdb;
-       struct ltdb_context *ltdb_ac;
-       int tret, ret = LDB_SUCCESS;
-
-       ltdb = talloc_get_type(module->private_data, struct ltdb_private);
-
-       if (check_critical_controls(req->controls)) {
-               return LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION;
-       }
+       struct ldb_module *module = ctx->module;
+       struct ldb_request *req = ctx->req;
+       int tret;
 
-       req->handle = init_ltdb_handle(ltdb, module, req);
-       if (req->handle == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-       ltdb_ac = talloc_get_type(req->handle->private_data, struct ltdb_context);
+       req->handle->state = LDB_ASYNC_PENDING;
 
        tret = ltdb_add_internal(module, req->op.add.message);
        if (tret != LDB_SUCCESS) {
-               req->handle->status = tret;
-               goto done;
+               return tret;
        }
 
-       if (ltdb_ac->callback) {
-               ret = ltdb_ac->callback(module->ldb, ltdb_ac->context, NULL);
-       }
-done:
-       req->handle->state = LDB_ASYNC_DONE;
-       return ret;
+       return LDB_SUCCESS;
 }
 
 /*
@@ -402,42 +356,24 @@ done:
 /*
   delete a record from the database
 */
-static int ltdb_delete(struct ldb_module *module, struct ldb_request *req)
+static int ltdb_delete(struct ltdb_context *ctx)
 {
-       struct ltdb_private *ltdb;
-       struct ltdb_context *ltdb_ac;
-       int tret, ret = LDB_SUCCESS;
-
-       ltdb = talloc_get_type(module->private_data, struct ltdb_private);
-
-       if (check_critical_controls(req->controls)) {
-               return LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION;
-       }
+       struct ldb_module *module = ctx->module;
+       struct ldb_request *req = ctx->req;
+       int tret;
 
-       req->handle = NULL;
+       req->handle->state = LDB_ASYNC_PENDING;
 
        if (ltdb_cache_load(module) != 0) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       req->handle = init_ltdb_handle(ltdb, module, req);
-       if (req->handle == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-       ltdb_ac = talloc_get_type(req->handle->private_data, struct ltdb_context);
-
        tret = ltdb_delete_internal(module, req->op.del.dn);
        if (tret != LDB_SUCCESS) {
-               req->handle->status = tret;
-               goto done;
+               return tret;
        }
 
-       if (ltdb_ac->callback) {
-               ret = ltdb_ac->callback(module->ldb, ltdb_ac->context, NULL);
-       }
-done:
-       req->handle->state = LDB_ASYNC_DONE;
-       return ret;
+       return LDB_SUCCESS;
 }
 
 /*
@@ -784,83 +720,50 @@ failed:
 /*
   modify a record
 */
-static int ltdb_modify(struct ldb_module *module, struct ldb_request *req)
+static int ltdb_modify(struct ltdb_context *ctx)
 {
-       struct ltdb_private *ltdb;
-       struct ltdb_context *ltdb_ac;
-       int tret, ret = LDB_SUCCESS;
-
-       ltdb = talloc_get_type(module->private_data, struct ltdb_private);
-
-       if (check_critical_controls(req->controls)) {
-               return LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION;
-       }
-
-       req->handle = NULL;
+       struct ldb_module *module = ctx->module;
+       struct ldb_request *req = ctx->req;
+       int tret;
 
-       req->handle = init_ltdb_handle(ltdb, module, req);
-       if (req->handle == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-       ltdb_ac = talloc_get_type(req->handle->private_data, struct ltdb_context);
+       req->handle->state = LDB_ASYNC_PENDING;
 
        tret = ltdb_check_special_dn(module, req->op.mod.message);
        if (tret != LDB_SUCCESS) {
-               req->handle->status = tret;
-               goto done;
+               return tret;
        }
 
        if (ltdb_cache_load(module) != 0) {
-               ret = LDB_ERR_OPERATIONS_ERROR;
-               goto done;
+               return LDB_ERR_OPERATIONS_ERROR;
        }
 
        tret = ltdb_modify_internal(module, req->op.mod.message);
        if (tret != LDB_SUCCESS) {
-               req->handle->status = tret;
-               goto done;
+               return tret;
        }
 
-       if (ltdb_ac->callback) {
-               ret = ltdb_ac->callback(module->ldb, ltdb_ac->context, NULL);
-       }
-done:
-       req->handle->state = LDB_ASYNC_DONE;
-       return ret;
+       return LDB_SUCCESS;
 }
 
 /*
   rename a record
 */
-static int ltdb_rename(struct ldb_module *module, struct ldb_request *req)
+static int ltdb_rename(struct ltdb_context *ctx)
 {
-       struct ltdb_private *ltdb;
-       struct ltdb_context *ltdb_ac;
+       struct ldb_module *module = ctx->module;
+       struct ldb_request *req = ctx->req;
        struct ldb_message *msg;
-       int tret, ret = LDB_SUCCESS;
-
-       ltdb = talloc_get_type(module->private_data, struct ltdb_private);
-
-       if (check_critical_controls(req->controls)) {
-               return LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION;
-       }
-
-       req->handle = NULL;
+       int tret;
 
-       if (ltdb_cache_load(module) != 0) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
+       req->handle->state = LDB_ASYNC_PENDING;
 
-       req->handle = init_ltdb_handle(ltdb, module, req);
-       if (req->handle == NULL) {
+       if (ltdb_cache_load(ctx->module) != 0) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       ltdb_ac = talloc_get_type(req->handle->private_data, struct ltdb_context);
 
-       msg = talloc(ltdb_ac, struct ldb_message);
+       msg = talloc(ctx, struct ldb_message);
        if (msg == NULL) {
-               ret = LDB_ERR_OPERATIONS_ERROR;
-               goto done;
+               return LDB_ERR_OPERATIONS_ERROR;
        }
 
        /* in case any attribute of the message was indexed, we need
@@ -868,14 +771,12 @@ static int ltdb_rename(struct ldb_module *module, struct ldb_request *req)
        tret = ltdb_search_dn1(module, req->op.rename.olddn, msg);
        if (tret != LDB_SUCCESS) {
                /* not finding the old record is an error */
-               req->handle->status = tret;
-               goto done;
+               return tret;
        }
 
        msg->dn = ldb_dn_copy(msg, req->op.rename.newdn);
        if (!msg->dn) {
-               ret = LDB_ERR_OPERATIONS_ERROR;
-               goto done;
+               return LDB_ERR_OPERATIONS_ERROR;
        }
 
        if (ldb_dn_compare(req->op.rename.olddn, req->op.rename.newdn) == 0) {
@@ -886,38 +787,32 @@ static int ltdb_rename(struct ldb_module *module, struct ldb_request *req)
                   The only drawback to this is that if the delete
                   succeeds but the add fails, we rely on the
                   transaction to roll this all back. */
-               ret = ltdb_delete_internal(module, req->op.rename.olddn);
-               if (ret != LDB_SUCCESS) {
-                       goto done;
+               tret = ltdb_delete_internal(module, req->op.rename.olddn);
+               if (tret != LDB_SUCCESS) {
+                       return tret;
                }
 
-               ret = ltdb_add_internal(module, msg);
-               if (ret != LDB_SUCCESS) {
-                       goto done;
+               tret = ltdb_add_internal(module, msg);
+               if (tret != LDB_SUCCESS) {
+                       return tret;
                }
        } else {
                /* The rename operation is changing DNs.  Try to add the new
                   DN first to avoid clobbering another DN not related to
                   this rename operation. */
-               ret = ltdb_add_internal(module, msg);
-               if (ret != LDB_SUCCESS) {
-                       goto done;
+               tret = ltdb_add_internal(module, msg);
+               if (tret != LDB_SUCCESS) {
+                       return tret;
                }
 
                tret = ltdb_delete_internal(module, req->op.rename.olddn);
                if (tret != LDB_SUCCESS) {
                        ltdb_delete_internal(module, req->op.rename.newdn);
-                       ret = LDB_ERR_OPERATIONS_ERROR;
-                       goto done;
+                       return LDB_ERR_OPERATIONS_ERROR;
                }
        }
 
-       if (ltdb_ac->callback) {
-               ret = ltdb_ac->callback(module->ldb, ltdb_ac->context, NULL);
-       }
-done:
-       req->handle->state = LDB_ASYNC_DONE;
-       return ret;
+       return LDB_SUCCESS;
 }
 
 static int ltdb_start_trans(struct ldb_module *module)
@@ -962,24 +857,6 @@ static int ltdb_del_trans(struct ldb_module *module)
        return LDB_SUCCESS;
 }
 
-static int ltdb_wait(struct ldb_handle *handle, enum ldb_wait_type type)
-{
-       return handle->status;
-}
-
-static int ltdb_request(struct ldb_module *module, struct ldb_request *req)
-{
-       /* check for oustanding critical controls
-        * and return an error if found */
-       if (check_critical_controls(req->controls)) {
-               return LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION;
-       }
-
-       /* search, add, modify, delete, rename are handled by their own,
-        * no other op supported */
-       return LDB_ERR_OPERATIONS_ERROR;
-}
-
 /*
   return sequenceNumber from @BASEINFO
 */
@@ -1013,7 +890,7 @@ static int ltdb_sequence_number(struct ldb_module *module,
                talloc_free(tmp_ctx);
                /* zero is as good as anything when we don't know */
                req->op.seq_num.seq_num = 0;
-               return LDB_SUCCESS;
+               return tret;
        }
 
        switch (req->op.seq_num.type) {
@@ -1034,22 +911,136 @@ static int ltdb_sequence_number(struct ldb_module *module,
                }
                break;
        }
+
        talloc_free(tmp_ctx);
+
+       return LDB_SUCCESS;
+}
+
+void ltdb_request_done(struct ldb_request *req, int error)
+{
+       struct ldb_reply *ares;
+
+       /* if we already returned an error just return */
+       if (req->handle->status != LDB_SUCCESS) {
+               return;
+       }
+
+       ares = talloc_zero(req, struct ldb_reply);
+       if (!ares) {
+               ldb_oom(req->handle->ldb);
+               req->callback(req, NULL);
+               return;
+       }
+       ares->type = LDB_REPLY_DONE;
+       ares->error = error;
+
+       req->callback(req, ares);
+}
+
+static void ltdb_timeout(struct event_context *ev,
+                         struct timed_event *te,
+                         struct timeval t,
+                         void *private_data)
+{
+       struct ltdb_context *ctx;
+       ctx = talloc_get_type(private_data, struct ltdb_context);
+
+       ltdb_request_done(ctx->req, LDB_ERR_TIME_LIMIT_EXCEEDED);
+}
+
+static void ltdb_callback(struct event_context *ev,
+                         struct timed_event *te,
+                         struct timeval t,
+                         void *private_data)
+{
+       struct ltdb_context *ctx;
+       int ret;
+
+       ctx = talloc_get_type(private_data, struct ltdb_context);
+
+       switch (ctx->req->operation) {
+       case LDB_SEARCH:
+               ret = ltdb_search(ctx);
+               break;
+       case LDB_ADD:
+               ret = ltdb_add(ctx);
+               break;
+       case LDB_MODIFY:
+               ret = ltdb_modify(ctx);
+               break;
+       case LDB_DELETE:
+               ret = ltdb_delete(ctx);
+               break;
+       case LDB_RENAME:
+               ret = ltdb_rename(ctx);
+               break;
+       default:
+               /* no other op supported */
+               ret = LDB_ERR_UNWILLING_TO_PERFORM;
+       }
+
+       if (!ctx->callback_failed) {
+               ltdb_request_done(ctx->req, ret);
+       }
+}
+
+static int ltdb_handle_request(struct ldb_module *module,
+                               struct ldb_request *req)
+{
+       struct event_context *ev;
+       struct ltdb_context *ac;
+       struct timed_event *te;
+       struct timeval tv;
+
+       if (check_critical_controls(req->controls)) {
+               return LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION;
+       }
+
+       if (req->starttime == 0 || req->timeout == 0) {
+               ldb_set_errstring(module->ldb, "Invalid timeout settings");
+               return LDB_ERR_TIME_LIMIT_EXCEEDED;
+       }
+
+       ev = ldb_get_event_context(module->ldb);
+
+       ac = talloc_zero(req, struct ltdb_context);
+       if (ac == NULL) {
+               ldb_set_errstring(module->ldb, "Out of Memory");
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       ac->module = module;
+       ac->req = req;
+
+       tv.tv_sec = 0;
+       tv.tv_usec = 0;
+       te = event_add_timed(ev, ac, tv, ltdb_callback, ac);
+       if (NULL == te) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+
+       tv.tv_sec = req->starttime + req->timeout;
+       te = event_add_timed(ev, ac, tv, ltdb_timeout, ac);
+       if (NULL == te) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
        return LDB_SUCCESS;
 }
 
 static const struct ldb_module_ops ltdb_ops = {
        .name              = "tdb",
-       .search            = ltdb_search,
-       .add               = ltdb_add,
-       .modify            = ltdb_modify,
-       .del               = ltdb_delete,
-       .rename            = ltdb_rename,
-       .request           = ltdb_request,
+       .search            = ltdb_handle_request,
+       .add               = ltdb_handle_request,
+       .modify            = ltdb_handle_request,
+       .del               = ltdb_handle_request,
+       .rename            = ltdb_handle_request,
+/*     .request           = ltdb_handle_request, */
        .start_transaction = ltdb_start_trans,
        .end_transaction   = ltdb_end_trans,
        .del_transaction   = ltdb_del_trans,
-       .wait              = ltdb_wait,
        .sequence_number   = ltdb_sequence_number
 };
 
@@ -1114,7 +1105,7 @@ static int ltdb_connect(struct ldb_context *ldb, const char *url,
        ltdb->sequence_number = 0;
 
        *module = talloc(ldb, struct ldb_module);
-       if (!module) {
+       if ((*module) == NULL) {
                ldb_oom(ldb);
                talloc_free(ltdb);
                return -1;
index 4beced30eb77b42ad9f76d505223b9301d88a5bf..223181ca0bd20bf1486ee3cc8ec4ce607fba220f 100644 (file)
@@ -41,16 +41,15 @@ struct ltdb_private {
 */
 struct ltdb_context {
        struct ldb_module *module;
+       struct ldb_request *req;
+
+       bool callback_failed;
 
        /* search stuff */
        const struct ldb_parse_tree *tree;
        struct ldb_dn *base;
        enum ldb_scope scope;
        const char * const *attrs;
-
-       /* async stuff */
-       void *context;
-       int (*callback)(struct ldb_context *, void *, struct ldb_reply *);
 };
 
 /* special record types */
@@ -80,7 +79,7 @@ int ltdb_check_at_attributes_values(const struct ldb_val *value);
 
 struct ldb_parse_tree;
 
-int ltdb_search_indexed(struct ldb_handle *handle);
+int ltdb_search_indexed(struct ltdb_context *ctx);
 int ltdb_index_add(struct ldb_module *module, const struct ldb_message *msg);
 int ltdb_index_del(struct ldb_module *module, const struct ldb_message *msg);
 int ltdb_index_one(struct ldb_module *module, const struct ldb_message *msg, int add);
@@ -110,11 +109,9 @@ int ltdb_add_attr_results(struct ldb_module *module,
                          unsigned int *count, 
                          struct ldb_message ***res);
 int ltdb_filter_attrs(struct ldb_message *msg, const char * const *attrs);
-int ltdb_search(struct ldb_module *module, struct ldb_request *req);
+int ltdb_search(struct ltdb_context *ctx);
 
 /* The following definitions come from lib/ldb/ldb_tdb/ldb_tdb.c  */
-struct ldb_handle *init_ltdb_handle(struct ltdb_private *ltdb, struct ldb_module *module,
-                                   struct ldb_request *req);
 struct TDB_DATA ltdb_key(struct ldb_module *module, struct ldb_dn *dn);
 int ltdb_store(struct ldb_module *module, const struct ldb_message *msg, int flgs);
 int ltdb_delete_noindex(struct ldb_module *module, struct ldb_dn *dn);
@@ -127,4 +124,3 @@ struct tdb_context *ltdb_wrap_open(TALLOC_CTX *mem_ctx,
                                   const char *path, int hash_size, int tdb_flags,
                                   int open_flags, mode_t mode,
                                   struct ldb_context *ldb);
-
index c15fd2b9ae6f29b6ab003cd9a3dc557cef38a5ac..cc8099f27f5391a22a992a7a15088e388a8405e2 100644 (file)
@@ -3156,15 +3156,14 @@ SWIGINTERN ldb_error ldb_search_ex(ldb *self,TALLOC_CTX *mem_ctx,ldb_dn *base,en
                            attrs,
                            controls,
                            res,
-                           ldb_search_default_callback);
+                           ldb_search_default_callback,
+                           NULL);
 
             if (ret != 0) {
                 talloc_free(res);
                 return ret;
             }
 
-            ldb_set_timeout(self, req, 0); /* use default timeout */
-                
             ret = ldb_request(self, req);
                 
             if (ret == 0) {
@@ -3506,22 +3505,6 @@ int py_module_del_transaction(struct ldb_module *mod)
     return LDB_SUCCESS;
 }
 
-int py_module_wait(struct ldb_handle *mod, enum ldb_wait_type wait_type)
-{
-    PyObject *py_ldb = mod->private_data;
-    PyObject *py_result;
-
-    py_result = PyObject_CallMethod(py_ldb, "wait", "i", wait_type);
-
-    if (py_result == NULL) {
-        return LDB_ERR_OPERATIONS_ERROR;
-    }
-
-    Py_DECREF(py_result);
-
-    return LDB_SUCCESS;
-}
-
 int py_module_sequence_number(struct ldb_module *mod, struct ldb_request *req)
 {
     PyObject *py_ldb = mod->private_data;
@@ -6665,7 +6648,6 @@ SWIGINTERN PyObject *_wrap_register_module(PyObject *SWIGUNUSEDPARM(self), PyObj
   arg1->start_transaction = py_module_start_transaction;
   arg1->end_transaction = py_module_end_transaction;
   arg1->del_transaction = py_module_del_transaction;
-  arg1->wait = py_module_wait;
   arg1->sequence_number = py_module_sequence_number;
   result = ldb_register_module((struct ldb_module_ops const *)arg1);
   if (result != 0) {
index 77ebcc5ff46632844b354b6d5054d8f379bace88..5653794a88b605a813855ac98b6349875aa7e858 100644 (file)
@@ -2,6 +2,6 @@
 # disable ldb_sqlite3 by default
 SMB_ENABLE(ldb_sqlite3, NO)
 
-if test x"$with_sqlite3_support" = x"yes"; then
-       SMB_ENABLE(ldb_sqlite3, YES)
-fi
+#if test x"$with_sqlite3_support" = x"yes"; then
+#      SMB_ENABLE(ldb_sqlite3, YES)
+#fi
index eb27263b16ffe2a0fc13f241665b4061bec36bc0..17896a006a313cbb1d5c39539acea5e28e16019d 100644 (file)
@@ -1,7 +1,7 @@
 /* 
    ldb database library
 
-   Copyright (C) Simo Sorce  2005
+   Copyright (C) Simo Sorce  2005-2008
 
      ** NOTE! The following LGPL license applies to the ldb
      ** library. This does NOT imply that all of Samba is released
 
 struct asq_context {
 
-       enum {ASQ_INIT, ASQ_SEARCH_BASE, ASQ_SEARCH_MULTI} step;
+       enum {ASQ_SEARCH_BASE, ASQ_SEARCH_MULTI} step;
 
        struct ldb_module *module;
-       struct ldb_request *orig_req;
+       struct ldb_request *req;
 
        struct ldb_asq_control *asq_ctrl;
 
@@ -52,7 +52,6 @@ struct asq_context {
                ASQ_CTRL_AFFECTS_MULTIPLE_DSA           = 71
        } asq_ret;
 
-       struct ldb_request *base_req;
        struct ldb_reply *base_res;
 
        struct ldb_request **reqs;
@@ -62,192 +61,200 @@ struct asq_context {
        struct ldb_control **controls;
 };
 
-static struct ldb_handle *init_handle(struct ldb_request *req, struct ldb_module *module)
+static struct asq_context *asq_context_init(struct ldb_module *module, struct ldb_request *req)
 {
        struct asq_context *ac;
-       struct ldb_handle *h;
-
-       h = talloc_zero(req, struct ldb_handle);
-       if (h == NULL) {
-               ldb_set_errstring(module->ldb, "Out of Memory");
-               return NULL;
-       }
 
-       h->module = module;
-
-       ac = talloc_zero(h, struct asq_context);
+       ac = talloc_zero(req, struct asq_context);
        if (ac == NULL) {
-               ldb_set_errstring(module->ldb, "Out of Memory");
-               talloc_free(h);
+               ldb_oom(module->ldb);
                return NULL;
        }
 
-       h->private_data = (void *)ac;
-
-       h->state = LDB_ASYNC_INIT;
-       h->status = LDB_SUCCESS;
-
-       ac->step = ASQ_INIT;
        ac->module = module;
-       ac->orig_req = req;
+       ac->req = req;
 
-       return h;
+       return ac;
 }
 
-static int asq_terminate(struct ldb_handle *handle)
+static int asq_search_continue(struct asq_context *ac);
+
+static int asq_search_terminate(struct asq_context *ac)
 {
-       struct asq_context *ac;
-       struct ldb_reply *ares;
        struct ldb_asq_control *asq;
        int i;
 
-       ac = talloc_get_type(handle->private_data, struct asq_context);
-       if (ac == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       handle->status = LDB_SUCCESS;
-       handle->state = LDB_ASYNC_DONE;
-
-       ares = talloc_zero(ac, struct ldb_reply);
-       if (ares == NULL)
-               return LDB_ERR_OPERATIONS_ERROR;
-
-       ares->type = LDB_REPLY_DONE;
-
        if (ac->controls) {
-               for (i = 0; ac->controls[i]; i++);
-               ares->controls = talloc_move(ares, &ac->controls);
+               for (i = 0; ac->controls[i]; i++) /* count em */ ;
        } else {
                i = 0;
        }
 
-       ares->controls = talloc_realloc(ares, ares->controls, struct ldb_control *, i + 2);
-       
-       if (ares->controls == NULL)
+       ac->controls = talloc_realloc(ac, ac->controls, struct ldb_control *, i + 2);
+
+       if (ac->controls == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
+       }
 
-       ares->controls[i] = talloc(ares->controls, struct ldb_control);
-       if (ares->controls[i] == NULL)
+       ac->controls[i] = talloc(ac->controls, struct ldb_control);
+       if (ac->controls[i] == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
+       }
 
-       ares->controls[i]->oid = LDB_CONTROL_ASQ_OID;
-       ares->controls[i]->critical = 0;
+       ac->controls[i]->oid = LDB_CONTROL_ASQ_OID;
+       ac->controls[i]->critical = 0;
 
-       asq = talloc_zero(ares->controls[i], struct ldb_asq_control);
+       asq = talloc_zero(ac->controls[i], struct ldb_asq_control);
        if (asq == NULL)
                return LDB_ERR_OPERATIONS_ERROR;
 
        asq->result = ac->asq_ret;
-       
-       ares->controls[i]->data = asq;
 
-       ares->controls[i + 1] = NULL;
+       ac->controls[i]->data = asq;
 
-       ac->orig_req->callback(ac->module->ldb, ac->orig_req->context, ares);
+       ac->controls[i + 1] = NULL;
 
-       return LDB_SUCCESS;
+       return ldb_module_done(ac->req, ac->controls, NULL, LDB_SUCCESS);
 }
 
-static int asq_base_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares)
+static int asq_base_callback(struct ldb_request *req, struct ldb_reply *ares)
 {
        struct asq_context *ac;
+       int ret;
 
-       if (!context || !ares) {
-               ldb_set_errstring(ldb, "NULL Context or Result in callback");
-               goto error;
-       }
+       ac = talloc_get_type(req->context, struct asq_context);
 
-       ac = talloc_get_type(context, struct asq_context);
-       if (ac == NULL) {
-               goto error;
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
        }
 
-       /* we are interested only in the single reply (base search) we receive here */
-       if (ares->type == LDB_REPLY_ENTRY) {
+       switch (ares->type) {
+       case LDB_REPLY_ENTRY:
                ac->base_res = talloc_move(ac, &ares);
-       } else {
+               break;
+
+       case LDB_REPLY_REFERRAL:
+               /* ignore referrals */
                talloc_free(ares);
-       }
+               break;
 
+       case LDB_REPLY_DONE:
+
+               talloc_free(ares);
+
+               /* next step */
+               ret = asq_search_continue(ac);
+               if (ret != LDB_SUCCESS) {
+                       return ldb_module_done(ac->req, NULL, NULL, ret);
+               }
+               break;
+
+       }
        return LDB_SUCCESS;
-error:
-       talloc_free(ares);
-       return LDB_ERR_OPERATIONS_ERROR;
 }
 
-static int asq_reqs_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares)
+static int asq_reqs_callback(struct ldb_request *req, struct ldb_reply *ares)
 {
        struct asq_context *ac;
+       int ret;
 
-       if (!context || !ares) {
-               ldb_set_errstring(ldb, "NULL Context or Result in callback");
-               goto error;
-       }
+       ac = talloc_get_type(req->context, struct asq_context);
 
-       ac = talloc_get_type(context, struct asq_context);
-       if (ac == NULL) {
-               goto error;
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
        }
 
-       /* we are interested only in the single reply (base search) we receive here */
-       if (ares->type == LDB_REPLY_ENTRY) {
-
+       switch (ares->type) {
+       case LDB_REPLY_ENTRY:
                /* pass the message up to the original callback as we
                 * do not have to elaborate on it any further */
-               return ac->orig_req->callback(ac->module->ldb, ac->orig_req->context, ares);
-               
-       } else { /* ignore any REFERRAL or DONE reply */
+               ret = ldb_module_send_entry(ac->req, ares->message);
+               if (ret != LDB_SUCCESS) {
+                       return ldb_module_done(ac->req, NULL, NULL, ret);
+               }
+               talloc_free(ares);
+               break;
+
+       case LDB_REPLY_REFERRAL:
+               /* ignore referrals */
+               talloc_free(ares);
+               break;
+
+       case LDB_REPLY_DONE:
+
                talloc_free(ares);
+
+               ret = asq_search_continue(ac);
+               if (ret != LDB_SUCCESS) {
+                       return ldb_module_done(ac->req, NULL, NULL, ret);
+               }
+               break;
        }
 
        return LDB_SUCCESS;
-error:
-       talloc_free(ares);
-       return LDB_ERR_OPERATIONS_ERROR;
 }
 
-static int asq_build_first_request(struct asq_context *ac)
+static int asq_build_first_request(struct asq_context *ac, struct ldb_request **base_req)
 {
-       char **base_attrs;
+       const char **base_attrs;
+       int ret;
 
-       ac->base_req = talloc_zero(ac, struct ldb_request);
-       if (ac->base_req == NULL) return LDB_ERR_OPERATIONS_ERROR;
+       ac->req_attrs = ac->req->op.search.attrs;
+       ac->req_attribute = talloc_strdup(ac, ac->asq_ctrl->source_attribute);
+       if (ac->req_attribute == NULL)
+               return LDB_ERR_OPERATIONS_ERROR;
 
-       ac->base_req->operation = ac->orig_req->operation;
-       ac->base_req->op.search.base = ac->orig_req->op.search.base;
-       ac->base_req->op.search.scope = LDB_SCOPE_BASE;
-       ac->base_req->op.search.tree = ac->orig_req->op.search.tree;
-       base_attrs = talloc_array(ac->base_req, char *, 2);
+       base_attrs = talloc_array(ac, const char *, 2);
        if (base_attrs == NULL) return LDB_ERR_OPERATIONS_ERROR;
 
        base_attrs[0] = talloc_strdup(base_attrs, ac->asq_ctrl->source_attribute);
        if (base_attrs[0] == NULL) return LDB_ERR_OPERATIONS_ERROR;
 
        base_attrs[1] = NULL;
-       ac->base_req->op.search.attrs = (const char * const *)base_attrs;
 
-       ac->base_req->context = ac;
-       ac->base_req->callback = asq_base_callback;
-       ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->base_req);
+       ret = ldb_build_search_req_ex(base_req, ac->module->ldb, ac,
+                                       ac->req->op.search.base,
+                                       LDB_SCOPE_BASE,
+                                       ac->req->op.search.tree,
+                                       (const char * const *)base_attrs,
+                                       NULL,
+                                       ac, asq_base_callback,
+                                       ac->req);
+       if (ret != LDB_SUCCESS) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
 
        return LDB_SUCCESS;
 }
 
-static int asq_build_multiple_requests(struct asq_context *ac, struct ldb_handle *handle)
+static int asq_build_multiple_requests(struct asq_context *ac, bool *terminated)
 {
+       struct ldb_control **saved_controls;
+       struct ldb_control *control;
+       struct ldb_dn *dn;
        struct ldb_message_element *el;
-       int i;
+       int ret, i;
 
-       /* look up the DNs */
        if (ac->base_res == NULL) {
                return LDB_ERR_NO_SUCH_OBJECT;
        }
+
        el = ldb_msg_find_element(ac->base_res->message, ac->req_attribute);
        /* no values found */
        if (el == NULL) {
                ac->asq_ret = ASQ_CTRL_SUCCESS;
-               return asq_terminate(handle);
+               *terminated = true;
+               return asq_search_terminate(ac);
        }
 
        ac->num_reqs = el->num_values;
@@ -259,144 +266,75 @@ static int asq_build_multiple_requests(struct asq_context *ac, struct ldb_handle
 
        for (i = 0; i < el->num_values; i++) {
 
-               ac->reqs[i] = talloc_zero(ac->reqs, struct ldb_request);
-               if (ac->reqs[i] == NULL)
-                       return LDB_ERR_OPERATIONS_ERROR;
-               ac->reqs[i]->operation = LDB_SEARCH;
-               ac->reqs[i]->op.search.base = ldb_dn_new(ac->reqs[i], ac->module->ldb, (const char *)el->values[i].data);
-               if ( ! ldb_dn_validate(ac->reqs[i]->op.search.base)) {
+               dn = ldb_dn_new(ac, ac->module->ldb,
+                               (const char *)el->values[i].data);
+               if ( ! ldb_dn_validate(dn)) {
                        ac->asq_ret = ASQ_CTRL_INVALID_ATTRIBUTE_SYNTAX;
-                       return asq_terminate(handle);
+                       *terminated = true;
+                       return asq_search_terminate(ac);
+               }
+
+               ret = ldb_build_search_req_ex(&ac->reqs[i],
+                                               ac->module->ldb, ac,
+                                               dn, LDB_SCOPE_BASE,
+                                               ac->req->op.search.tree,
+                                               ac->req_attrs,
+                                               ac->req->controls,
+                                               ac, asq_reqs_callback,
+                                               ac->req);
+               if (ret != LDB_SUCCESS) {
+                       return LDB_ERR_OPERATIONS_ERROR;
                }
-               ac->reqs[i]->op.search.scope = LDB_SCOPE_BASE;
-               ac->reqs[i]->op.search.tree = ac->base_req->op.search.tree;
-               ac->reqs[i]->op.search.attrs = ac->req_attrs;
 
-               ac->reqs[i]->context = ac;
-               ac->reqs[i]->callback = asq_reqs_callback;
-               ldb_set_timeout_from_prev_req(ac->module->ldb, ac->base_req, ac->reqs[i]);
+               /* remove the ASQ control itself */
+               control = ldb_request_get_control(ac->req, LDB_CONTROL_ASQ_OID);
+               if (!save_controls(control, ac->reqs[i], &saved_controls)) {
+                       return LDB_ERR_OPERATIONS_ERROR;
+               }
        }
 
        return LDB_SUCCESS;
 }
 
-static int asq_search_continue(struct ldb_handle *handle)
+static int asq_search_continue(struct asq_context *ac)
 {
-       struct asq_context *ac;
+       bool terminated = false;
        int ret;
-    
-       if (!handle || !handle->private_data) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       if (handle->state == LDB_ASYNC_DONE) {
-               return handle->status;
-       }
-
-       ac = talloc_get_type(handle->private_data, struct asq_context);
-       if (ac == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
 
        switch (ac->step) {
-       case ASQ_INIT:
-               /* check the search is well formed */
-               if (ac->orig_req->op.search.scope != LDB_SCOPE_BASE) {
-                       ac->asq_ret = ASQ_CTRL_UNWILLING_TO_PERFORM;
-                       return asq_terminate(handle);
-               }
-
-               ac->req_attrs = ac->orig_req->op.search.attrs;
-               ac->req_attribute = talloc_strdup(ac, ac->asq_ctrl->source_attribute);
-               if (ac->req_attribute == NULL)
-                       return LDB_ERR_OPERATIONS_ERROR;
-
-               /* get the object to retrieve the DNs to search */
-               ret = asq_build_first_request(ac);
-               if (ret != LDB_SUCCESS) {
-                       return ret;
-               }
-       
-               ac->step = ASQ_SEARCH_BASE;
-
-               handle->state = LDB_ASYNC_PENDING;
-               handle->status = LDB_SUCCESS;
-
-               return ldb_request(ac->module->ldb, ac->base_req);
-
        case ASQ_SEARCH_BASE:
 
-               ret = ldb_wait(ac->base_req->handle, LDB_WAIT_NONE);
-               
-               if (ret != LDB_SUCCESS) {
-                       handle->status = ret;
-                       goto done;
-               }
-
-               if (ac->base_req->handle->status != LDB_SUCCESS) {
-                       handle->status = ac->base_req->handle->status;
-                       goto done;
+               /* build up the requests call chain */
+               ret = asq_build_multiple_requests(ac, &terminated);
+               if (ret != LDB_SUCCESS || terminated) {
+                       return ret;
                }
 
-               if (ac->base_req->handle->state == LDB_ASYNC_DONE) {
+               ac->step = ASQ_SEARCH_MULTI;
 
-                       /* build up the requests call chain */
-                       ret = asq_build_multiple_requests(ac, handle);
-                       if (ret != LDB_SUCCESS) {
-                               return ret;
-                       }
-                       if (handle->state == LDB_ASYNC_DONE) {
-                               return LDB_SUCCESS;
-                       }
-
-                       ac->step = ASQ_SEARCH_MULTI;
-
-                       return ldb_request(ac->module->ldb, ac->reqs[ac->cur_req]);
-               }
-
-               /* request still pending, return to cycle again */
-               return LDB_SUCCESS;
+               return ldb_request(ac->module->ldb, ac->reqs[ac->cur_req]);
 
        case ASQ_SEARCH_MULTI:
 
-               ret = ldb_wait(ac->reqs[ac->cur_req]->handle, LDB_WAIT_NONE);
-               
-               if (ret != LDB_SUCCESS) {
-                       handle->status = ret;
-                       goto done;
-               }
-               if (ac->reqs[ac->cur_req]->handle->status != LDB_SUCCESS) {
-                       handle->status = ac->reqs[ac->cur_req]->handle->status;
-               }
-
-               if (ac->reqs[ac->cur_req]->handle->state == LDB_ASYNC_DONE) {
-                       ac->cur_req++;
+               ac->cur_req++;
 
-                       if (ac->cur_req < ac->num_reqs) {
-                               return ldb_request(ac->module->ldb, ac->reqs[ac->cur_req]);
-                       }
-
-                       return asq_terminate(handle);
+               if (ac->cur_req == ac->num_reqs) {
+                       /* done */
+                       return asq_search_terminate(ac);
                }
 
-               /* request still pending, return to cycle again */
-               return LDB_SUCCESS;
-
-       default:
-               ret = LDB_ERR_OPERATIONS_ERROR;
-               break;
+               return ldb_request(ac->module->ldb, ac->reqs[ac->cur_req]);
        }
 
-done:
-       handle->state = LDB_ASYNC_DONE;
-       return ret;
+       return LDB_ERR_OPERATIONS_ERROR;
 }
 
 static int asq_search(struct ldb_module *module, struct ldb_request *req)
 {
+       struct ldb_request *base_req;
        struct ldb_control *control;
        struct asq_context *ac;
-       struct ldb_handle *h;
+       int ret;
 
        /* check if there's a paged request control */
        control = ldb_request_get_control(req, LDB_CONTROL_ASQ_OID);
@@ -405,67 +343,37 @@ static int asq_search(struct ldb_module *module, struct ldb_request *req)
                return ldb_next_request(module, req);
        }
 
-       req->handle = NULL;
-
-       if (!req->callback || !req->context) {
-               ldb_set_errstring(module->ldb,
-                                 "Async interface called with NULL callback function or NULL context");
+       ac = asq_context_init(module, req);
+       if (!ac) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       h = init_handle(req, module);
-       if (!h) {
-               return LDB_ERR_OPERATIONS_ERROR;
+       /* check the search is well formed */
+       if (req->op.search.scope != LDB_SCOPE_BASE) {
+               ac->asq_ret = ASQ_CTRL_UNWILLING_TO_PERFORM;
+               return asq_search_terminate(ac);
        }
-       ac = talloc_get_type(h->private_data, struct asq_context);
 
        ac->asq_ctrl = talloc_get_type(control->data, struct ldb_asq_control);
        if (!ac->asq_ctrl) {
                return LDB_ERR_PROTOCOL_ERROR;
        }
 
-       req->handle = h;
-
-       return asq_search_continue(h);
-}
-
-static int asq_wait(struct ldb_handle *handle, enum ldb_wait_type type)
-{
-       int ret;
-
-       if (!handle || !handle->private_data) {
-               return LDB_ERR_OPERATIONS_ERROR;
+       ret = asq_build_first_request(ac, &base_req);
+       if (ret != LDB_SUCCESS) {
+               return ret;
        }
 
-       if (type == LDB_WAIT_ALL) {
-               while (handle->state != LDB_ASYNC_DONE) {
-                       ret = asq_search_continue(handle);
-                       if (ret != LDB_SUCCESS) {
-                               return ret;
-                       }
-               }
-
-               return handle->status;
-       }
+       ac->step = ASQ_SEARCH_BASE;
 
-       return asq_search_continue(handle);
+       return ldb_request(module->ldb, base_req);
 }
 
 static int asq_init(struct ldb_module *module)
 {
-       struct ldb_request *req;
        int ret;
 
-       req = talloc_zero(module, struct ldb_request);
-       if (req == NULL) {
-               ldb_debug(module->ldb, LDB_DEBUG_ERROR, "asq: Out of memory!\n");
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       req->operation = LDB_REQ_REGISTER_CONTROL;
-       req->op.reg_control.oid = LDB_CONTROL_ASQ_OID;
-
-       ret = ldb_request(module->ldb, req);
+       ret = ldb_mod_register_control(module, LDB_CONTROL_ASQ_OID);
        if (ret != LDB_SUCCESS) {
                ldb_debug(module->ldb, LDB_DEBUG_WARNING, "asq: Unable to register control with rootdse!\n");
        }
@@ -476,6 +384,5 @@ static int asq_init(struct ldb_module *module)
 const struct ldb_module_ops ldb_asq_module_ops = {
        .name              = "asq",
        .search            = asq_search,
-       .wait              = asq_wait,
        .init_context      = asq_init
 };
index a59e81becdd4e50eb764484eba6b2ae1a27254ce..abb1d4ca1af66a4ea10db59e9acea69c6d848a8a 100644 (file)
@@ -2,7 +2,7 @@
    ldb database library
 
    Copyright (C) Andrew Tridgell 2005
-   Copyright (C) Simo Sorce 2006
+   Copyright (C) Simo Sorce 2006-2008
 
      ** NOTE! The following LGPL license applies to the ldb
      ** library. This does NOT imply that all of Samba is released
@@ -173,38 +173,53 @@ failed:
 */
 
 struct operational_context {
-
        struct ldb_module *module;
-       void *up_context;
-       int (*up_callback)(struct ldb_context *, void *, struct ldb_reply *);
+       struct ldb_request *req;
 
        const char * const *attrs;
 };
 
-static int operational_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares)
+static int operational_callback(struct ldb_request *req, struct ldb_reply *ares)
 {
        struct operational_context *ac;
+       int ret;
 
-       if (!context || !ares) {
-               ldb_set_errstring(ldb, "NULL Context or Result in callback");
-               goto error;
-       }
+       ac = talloc_get_type(req->context, struct operational_context);
 
-       ac = talloc_get_type(context, struct operational_context);
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
 
-       if (ares->type == LDB_REPLY_ENTRY) {
+       switch (ares->type) {
+       case LDB_REPLY_ENTRY:
                /* for each record returned post-process to add any derived
                   attributes that have been asked for */
-               if (operational_search_post_process(ac->module, ares->message, ac->attrs) != 0) {
-                       goto error;
+               ret = operational_search_post_process(ac->module,
+                                                       ares->message,
+                                                       ac->attrs);
+               if (ret != 0) {
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
                }
-       }
+               return ldb_module_send_entry(ac->req, ares->message);
 
-       return ac->up_callback(ldb, ac->up_context, ares);
+       case LDB_REPLY_REFERRAL:
+               /* ignore referrals */
+               break;
+
+       case LDB_REPLY_DONE:
+
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, LDB_SUCCESS);
+       }
 
-error:
        talloc_free(ares);
-       return LDB_ERR_OPERATIONS_ERROR;
+       return LDB_SUCCESS;
 }
 
 static int operational_search(struct ldb_module *module, struct ldb_request *req)
@@ -212,9 +227,8 @@ static int operational_search(struct ldb_module *module, struct ldb_request *req
        struct operational_context *ac;
        struct ldb_request *down_req;
        const char **search_attrs = NULL;
-       int i, a, ret;
-
-       req->handle = NULL;
+       int i, a;
+       int ret;
 
        ac = talloc(req, struct operational_context);
        if (ac == NULL) {
@@ -222,21 +236,10 @@ static int operational_search(struct ldb_module *module, struct ldb_request *req
        }
 
        ac->module = module;
-       ac->up_context = req->context;
-       ac->up_callback = req->callback;
+       ac->req = req;
        ac->attrs = req->op.search.attrs;
 
-       down_req = talloc_zero(req, struct ldb_request);
-       if (down_req == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       down_req->operation = req->operation;
-       down_req->op.search.base = req->op.search.base;
-       down_req->op.search.scope = req->op.search.scope;
-       down_req->op.search.tree = req->op.search.tree;
-
-       /*  FIXME: I hink we should copy the tree and keep the original
+       /*  FIXME: We must copy the tree and keep the original
         *  unmodified. SSS */
        /* replace any attributes in the parse tree that are
           searchable, but are stored using a different name in the
@@ -264,27 +267,26 @@ static int operational_search(struct ldb_module *module, struct ldb_request *req
                        }
                }
        }
-       
-       /* use new set of attrs if any */
-       if (search_attrs) down_req->op.search.attrs = search_attrs;
-       else down_req->op.search.attrs = req->op.search.attrs;
-       
-       down_req->controls = req->controls;
-
-       down_req->context = ac;
-       down_req->callback = operational_callback;
-       ldb_set_timeout_from_prev_req(module->ldb, req, down_req);
 
-       /* perform the search */
-       ret = ldb_next_request(module, down_req);
+       /* use new set of attrs if any */
+       if (search_attrs == NULL) {
+               search_attrs = req->op.search.attrs;
+       }
 
-       /* do not free down_req as the call results may be linked to it,
-        * it will be freed when the upper level request get freed */
-       if (ret == LDB_SUCCESS) {
-               req->handle = down_req->handle;
+       ret = ldb_build_search_req_ex(&down_req, module->ldb, ac,
+                                       req->op.search.base,
+                                       req->op.search.scope,
+                                       req->op.search.tree,
+                                       (const char * const *)search_attrs,
+                                       req->controls,
+                                       ac, operational_callback,
+                                       req);
+       if (ret != LDB_SUCCESS) {
+               return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       return ret;
+       /* perform the search */
+       return ldb_next_request(module, down_req);
 }
 
 static int operational_init(struct ldb_module *ctx)
index b62b1f92cbd7d0271fffbbef452664bfb89662fe..d3bb83bbcd9ec6bbe8a568784b8b226b0252b8cc 100644 (file)
@@ -1,7 +1,7 @@
 /* 
    ldb database library
 
-   Copyright (C) Simo Sorce  2005-2006
+   Copyright (C) Simo Sorce  2005-2008
 
      ** NOTE! The following LGPL license applies to the ldb
      ** library. This does NOT imply that all of Samba is released
@@ -51,9 +51,8 @@ struct results_store {
        char *cookie;
        time_t timestamp;
 
-       struct results_store *prev;
        struct results_store *next;
-       
+
        struct message_store *first;
        struct message_store *last;
        int num_entries;
@@ -62,8 +61,6 @@ struct results_store {
        struct message_store *last_ref;
 
        struct ldb_control **controls;
-
-       struct ldb_request *req;
 };
 
 struct private_data {
@@ -73,20 +70,25 @@ struct private_data {
        
 };
 
-int store_destructor(struct results_store *store)
+int store_destructor(struct results_store *del)
 {
-       if (store->prev) {
-               store->prev->next = store->next;
-       }
-       if (store->next) {
-               store->next->prev = store->prev;
+       struct private_data *priv = del->priv;
+       struct results_store *loop;
+
+       if (priv->store == del) {
+               priv->store = del->next;
+               return 0;
        }
 
-       if (store == store->priv->store) {
-               store->priv->store = NULL;
+       for (loop = priv->store; loop; loop = loop->next) {
+               if (loop->next == del) {
+                       loop->next = del->next;
+                       return 0;
+               }
        }
 
-       return 0;
+       /* is not in list ? */
+       return -1;
 }
 
 static struct results_store *new_store(struct private_data *priv)
@@ -116,10 +118,7 @@ static struct results_store *new_store(struct private_data *priv)
        newr->first_ref = NULL;
        newr->controls = NULL;
 
-       /* put this entry as first */
-       newr->prev = NULL;
        newr->next = priv->store;
-       if (priv->store != NULL) priv->store->prev = newr;
        priv->store = newr;
 
        talloc_set_destructor(newr, store_destructor);
@@ -129,101 +128,164 @@ static struct results_store *new_store(struct private_data *priv)
 
 struct paged_context {
        struct ldb_module *module;
-       void *up_context;
-       int (*up_callback)(struct ldb_context *, void *, struct ldb_reply *);
-
-       int size;
+       struct ldb_request *req;
 
        struct results_store *store;
+       int size;
+       struct ldb_control **controls;
 };
 
-static struct ldb_handle *init_handle(void *mem_ctx, struct ldb_module *module,
-                                           void *context,
-                                           int (*callback)(struct ldb_context *, void *, struct ldb_reply *))
+static int paged_results(struct paged_context *ac)
 {
-       struct paged_context *ac;
-       struct ldb_handle *h;
+       struct ldb_paged_control *paged;
+       struct message_store *msg;
+       int i, num_ctrls, ret;
 
-       h = talloc_zero(mem_ctx, struct ldb_handle);
-       if (h == NULL) {
-               ldb_set_errstring(module->ldb, "Out of Memory");
-               return NULL;
+       if (ac->store == NULL) {
+               return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       h->module = module;
+       while (ac->store->num_entries > 0 && ac->size > 0) {
+               msg = ac->store->first;
+               ret = ldb_module_send_entry(ac->req, msg->r->message);
+               if (ret != LDB_SUCCESS) {
+                       return ret;
+               }
 
-       ac = talloc_zero(h, struct paged_context);
-       if (ac == NULL) {
-               ldb_set_errstring(module->ldb, "Out of Memory");
-               talloc_free(h);
-               return NULL;
+               ac->store->first = msg->next;
+               talloc_free(msg);
+               ac->store->num_entries--;
+               ac->size--;
        }
 
-       h->private_data = (void *)ac;
+       while (ac->store->first_ref != NULL) {
+               msg = ac->store->first_ref;
+               ret = ldb_module_send_referral(ac->req, msg->r->referral);
+               if (ret != LDB_SUCCESS) {
+                       return ret;
+               }
 
-       h->state = LDB_ASYNC_INIT;
-       h->status = LDB_SUCCESS;
+               ac->store->first_ref = msg->next;
+               talloc_free(msg);
+       }
 
-       ac->module = module;
-       ac->up_context = context;
-       ac->up_callback = callback;
+       /* return result done */
+       num_ctrls = 1;
+       i = 0;
+
+       if (ac->store->controls != NULL) {
+               while (ac->store->controls[i]) i++; /* counting */
+
+               num_ctrls += i;
+       }
+
+       ac->controls = talloc_array(ac, struct ldb_control *, num_ctrls +1);
+       if (ac->controls == NULL) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+       ac->controls[num_ctrls] = NULL;
+
+       for (i = 0; i < (num_ctrls -1); i++) {
+               ac->controls[i] = talloc_reference(ac->controls, ac->store->controls[i]);
+       }
+
+       ac->controls[i] = talloc(ac->controls, struct ldb_control);
+       if (ac->controls[i] == NULL) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
 
-       return h;
+       ac->controls[i]->oid = talloc_strdup(ac->controls[i],
+                                               LDB_CONTROL_PAGED_RESULTS_OID);
+       if (ac->controls[i]->oid == NULL) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       ac->controls[i]->critical = 0;
+
+       paged = talloc(ac->controls[i], struct ldb_paged_control);
+       if (paged == NULL) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       ac->controls[i]->data = paged;
+
+       if (ac->size > 0) {
+               paged->size = 0;
+               paged->cookie = NULL;
+               paged->cookie_len = 0;
+       } else {
+               paged->size = ac->store->num_entries;
+               paged->cookie = talloc_strdup(paged, ac->store->cookie);
+               paged->cookie_len = strlen(paged->cookie) + 1;
+       }
+
+       return LDB_SUCCESS;
 }
 
-static int paged_search_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares)
+static int paged_search_callback(struct ldb_request *req, struct ldb_reply *ares)
 {
-       struct paged_context *ac = NULL;
+       struct paged_context *ac ;
+       struct message_store *msg_store;
+       int ret;
 
-       if (!context || !ares) {
-               ldb_set_errstring(ldb, "NULL Context or Result in callback");
-               goto error;
+       ac = talloc_get_type(req->context, struct paged_context);
+
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
        }
 
-       ac = talloc_get_type(context, struct paged_context);
+       switch (ares->type) {
+       case LDB_REPLY_ENTRY:
+               msg_store = talloc(ac->store, struct message_store);
+               if (msg_store == NULL) {
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
+               }
+               msg_store->next = NULL;
+               msg_store->r = talloc_steal(msg_store, ares);
 
-       if (ares->type == LDB_REPLY_ENTRY) {
                if (ac->store->first == NULL) {
-                       ac->store->first = ac->store->last = talloc(ac->store, struct message_store);
+                       ac->store->first = msg_store;
                } else {
-                       ac->store->last->next = talloc(ac->store, struct message_store);
-                       ac->store->last = ac->store->last->next;
-               }
-               if (ac->store->last == NULL) {
-                       goto error;
+                       ac->store->last->next = msg_store;
                }
+               ac->store->last = msg_store;
 
                ac->store->num_entries++;
 
-               ac->store->last->r = talloc_steal(ac->store->last, ares);
-               ac->store->last->next = NULL;
-       }
+               break;
+
+       case LDB_REPLY_REFERRAL:
+               msg_store = talloc(ac->store, struct message_store);
+               if (msg_store == NULL) {
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
+               }
+               msg_store->next = NULL;
+               msg_store->r = talloc_steal(msg_store, ares);
 
-       if (ares->type == LDB_REPLY_REFERRAL) {
                if (ac->store->first_ref == NULL) {
-                       ac->store->first_ref = ac->store->last_ref = talloc(ac->store, struct message_store);
+                       ac->store->first_ref = msg_store;
                } else {
-                       ac->store->last_ref->next = talloc(ac->store, struct message_store);
-                       ac->store->last_ref = ac->store->last_ref->next;
-               }
-               if (ac->store->last_ref == NULL) {
-                       goto error;
+                       ac->store->last_ref->next = msg_store;
                }
+               ac->store->last_ref = msg_store;
 
-               ac->store->last_ref->r = talloc_steal(ac->store->last, ares);
-               ac->store->last_ref->next = NULL;
-       }
+               break;
 
-       if (ares->type == LDB_REPLY_DONE) {
+       case LDB_REPLY_DONE:
                ac->store->controls = talloc_move(ac->store, &ares->controls);
-               talloc_free(ares);
+               ret = paged_results(ac);
+               return ldb_module_done(ac->req, ac->controls,
+                                       ares->response, ret);
        }
 
        return LDB_SUCCESS;
-
-error:
-       talloc_free(ares);
-       return LDB_ERR_OPERATIONS_ERROR;
 }
 
 static int paged_search(struct ldb_module *module, struct ldb_request *req)
@@ -232,8 +294,8 @@ static int paged_search(struct ldb_module *module, struct ldb_request *req)
        struct private_data *private_data;
        struct ldb_paged_control *paged_ctrl;
        struct ldb_control **saved_controls;
+       struct ldb_request *search_req;
        struct paged_context *ac;
-       struct ldb_handle *h;
        int ret;
 
        /* check if there's a paged request control */
@@ -243,65 +305,57 @@ static int paged_search(struct ldb_module *module, struct ldb_request *req)
                return ldb_next_request(module, req);
        }
 
-       private_data = talloc_get_type(module->private_data, struct private_data);
-
-       req->handle = NULL;
-
-       if (!req->callback || !req->context) {
-               ldb_set_errstring(module->ldb,
-                                 "Async interface called with NULL callback function or NULL context");
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-       
        paged_ctrl = talloc_get_type(control->data, struct ldb_paged_control);
        if (!paged_ctrl) {
                return LDB_ERR_PROTOCOL_ERROR;
        }
 
-       h = init_handle(req, module, req->context, req->callback);
-       if (!h) {
+       private_data = talloc_get_type(module->private_data, struct private_data);
+
+       ac = talloc_zero(req, struct paged_context);
+       if (ac == NULL) {
+               ldb_set_errstring(module->ldb, "Out of Memory");
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       ac = talloc_get_type(h->private_data, struct paged_context);
 
+       ac->module = module;
+       ac->req = req;
        ac->size = paged_ctrl->size;
 
        /* check if it is a continuation search the store */
        if (paged_ctrl->cookie_len == 0) {
-               
-               ac->store = new_store(private_data);
-               if (ac->store == NULL) {
-                       talloc_free(h);
-                       return LDB_ERR_UNWILLING_TO_PERFORM;
+               if (paged_ctrl->size == 0) {
+                       return LDB_ERR_OPERATIONS_ERROR;
                }
 
-               ac->store->req = talloc(ac->store, struct ldb_request);
-               if (!ac->store->req)
+               ac->store = new_store(private_data);
+               if (ac->store == NULL) {
                        return LDB_ERR_OPERATIONS_ERROR;
+               }
 
-               ac->store->req->operation = req->operation;
-               ac->store->req->op.search.base = req->op.search.base;
-               ac->store->req->op.search.scope = req->op.search.scope;
-               ac->store->req->op.search.tree = req->op.search.tree;
-               ac->store->req->op.search.attrs = req->op.search.attrs;
-               ac->store->req->controls = req->controls;
+               ret = ldb_build_search_req_ex(&search_req, module->ldb, ac,
+                                               req->op.search.base,
+                                               req->op.search.scope,
+                                               req->op.search.tree,
+                                               req->op.search.attrs,
+                                               req->controls,
+                                               ac,
+                                               paged_search_callback,
+                                               req);
 
                /* save it locally and remove it from the list */
                /* we do not need to replace them later as we
                 * are keeping the original req intact */
-               if (!save_controls(control, ac->store->req, &saved_controls)) {
+               if (!save_controls(control, search_req, &saved_controls)) {
                        return LDB_ERR_OPERATIONS_ERROR;
                }
 
-               ac->store->req->context = ac;
-               ac->store->req->callback = paged_search_callback;
-               ldb_set_timeout_from_prev_req(module->ldb, req, ac->store->req);
-
-               ret = ldb_next_request(module, ac->store->req);
+               return ldb_next_request(module, search_req);
 
        } else {
                struct results_store *current = NULL;
 
+               /* TODO: age out old outstanding requests */
                for (current = private_data->store; current; current = current->next) {
                        if (strcmp(current->cookie, paged_ctrl->cookie) == 0) {
                                current->timestamp = time(NULL);
@@ -309,249 +363,52 @@ static int paged_search(struct ldb_module *module, struct ldb_request *req)
                        }
                }
                if (current == NULL) {
-                       talloc_free(h);
                        return LDB_ERR_UNWILLING_TO_PERFORM;
                }
 
                ac->store = current;
-               ret = LDB_SUCCESS;
-       }
-
-       req->handle = h;
-
-       /* check if it is an abandon */
-       if (ac->size == 0) {
-               talloc_free(ac->store);
-               h->status = LDB_SUCCESS;
-               h->state = LDB_ASYNC_DONE;
-               return LDB_SUCCESS;
-       }
-
-       /* TODO: age out old outstanding requests */
-
-       return ret;
-
-}
-
-static int paged_results(struct ldb_handle *handle)
-{
-       struct paged_context *ac;
-       struct ldb_paged_control *paged;
-       struct ldb_reply *ares;
-       struct message_store *msg;
-       int i, num_ctrls, ret;
-
-       ac = talloc_get_type(handle->private_data, struct paged_context);
-
-       if (ac->store == NULL)
-               return LDB_ERR_OPERATIONS_ERROR;
 
-       while (ac->store->num_entries > 0 && ac->size > 0) {
-               msg = ac->store->first;
-               ret = ac->up_callback(ac->module->ldb, ac->up_context, msg->r);
-               if (ret != LDB_SUCCESS) {
-                       handle->status = ret;
-                       handle->state = LDB_ASYNC_DONE;
-                       return ret;
+               /* check if it is an abandon */
+               if (ac->size == 0) {
+                       return ldb_module_done(req, NULL, NULL,
+                                                               LDB_SUCCESS);
                }
 
-               ac->store->first = msg->next;
-               talloc_free(msg);
-               ac->store->num_entries--;
-               ac->size--;
-       }
-
-       handle->state = LDB_ASYNC_DONE;
-
-       while (ac->store->first_ref != NULL) {
-               msg = ac->store->first_ref;
-               ret = ac->up_callback(ac->module->ldb, ac->up_context, msg->r);
+               ret = paged_results(ac);
                if (ret != LDB_SUCCESS) {
-                       handle->status = ret;
-                       handle->state = LDB_ASYNC_DONE;
-                       return ret;
+                       return ldb_module_done(req, NULL, NULL, ret);
                }
-
-               ac->store->first_ref = msg->next;
-               talloc_free(msg);
-       }
-
-       ares = talloc_zero(ac->store, struct ldb_reply);
-       if (ares == NULL) {
-               handle->status = LDB_ERR_OPERATIONS_ERROR;
-               return handle->status;
-       }
-       num_ctrls = 2;
-       i = 0;
-
-       if (ac->store->controls != NULL) {
-               ares->controls = ac->store->controls;
-               while (ares->controls[i]) i++; /* counting */
-
-               ares->controls = talloc_move(ares, &ac->store->controls);
-               num_ctrls += i;
-       }
-
-       ares->controls = talloc_realloc(ares, ares->controls, struct ldb_control *, num_ctrls);
-       if (ares->controls == NULL) {
-               handle->status = LDB_ERR_OPERATIONS_ERROR;
-               return handle->status;
+               return ldb_module_done(req, ac->controls, NULL,
+                                                               LDB_SUCCESS);
        }
-
-       ares->controls[i] = talloc(ares->controls, struct ldb_control);
-       if (ares->controls[i] == NULL) {
-               handle->status = LDB_ERR_OPERATIONS_ERROR;
-               return handle->status;
-       }
-
-       ares->controls[i]->oid = talloc_strdup(ares->controls[i], LDB_CONTROL_PAGED_RESULTS_OID);
-       if (ares->controls[i]->oid == NULL) {
-               handle->status = LDB_ERR_OPERATIONS_ERROR;
-               return handle->status;
-       }
-               
-       ares->controls[i]->critical = 0;
-       ares->controls[i + 1] = NULL;
-
-       paged = talloc(ares->controls[i], struct ldb_paged_control);
-       if (paged == NULL) {
-               handle->status = LDB_ERR_OPERATIONS_ERROR;
-               return handle->status;
-       }
-       
-       ares->controls[i]->data = paged;
-
-       if (ac->size > 0) {
-               paged->size = 0;
-               paged->cookie = NULL;
-               paged->cookie_len = 0;
-       } else {
-               paged->size = ac->store->num_entries;
-               paged->cookie = talloc_strdup(paged, ac->store->cookie);
-               paged->cookie_len = strlen(paged->cookie) + 1;
-       }
-
-       ares->type = LDB_REPLY_DONE;
-
-       ret = ac->up_callback(ac->module->ldb, ac->up_context, ares);
-
-       handle->status = ret;
-
-       return ret;
-}
-
-static int paged_wait_once(struct ldb_handle *handle) {
-       struct paged_context *ac;
-       int ret;
-    
-       if (!handle || !handle->private_data) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       if (handle->state == LDB_ASYNC_DONE) {
-               return handle->status;
-       }
-
-       handle->state = LDB_ASYNC_PENDING;
-
-       ac = talloc_get_type(handle->private_data, struct paged_context);
-
-       if (ac->store->req->handle->state == LDB_ASYNC_DONE) {
-               /* if lower level is finished we do not need to call it anymore */
-               /* return all we have until size == 0 or we empty storage */
-               ret = paged_results(handle);
-
-               /* we are done, if num_entries is zero free the storage
-                * as that mean we delivered the last batch */
-               if (ac->store->num_entries == 0) {
-                       talloc_free(ac->store);
-               }
-
-               return ret;
-       }
-
-       ret = ldb_wait(ac->store->req->handle, LDB_WAIT_NONE);
-       if (ret != LDB_SUCCESS) {
-               handle->state = LDB_ASYNC_DONE;
-               handle->status = ret;
-               return ret;
-       }
-
-       handle->status = ret;
-
-       if (ac->store->num_entries >= ac->size ||
-           ac->store->req->handle->state == LDB_ASYNC_DONE) {
-
-               ret = paged_results(handle);
-
-               /* we are done, if num_entries is zero free the storage
-                * as that mean we delivered the last batch */
-               if (ac->store->num_entries == 0) {
-                       talloc_free(ac->store);
-               }
-       }
-
-       return ret;
-}
-
-static int paged_wait(struct ldb_handle *handle, enum ldb_wait_type type)
-{
-       int ret;
-       if (!handle || !handle->private_data) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       if (type == LDB_WAIT_ALL) {
-               while (handle->state != LDB_ASYNC_DONE) {
-                       ret = paged_wait_once(handle);
-                       if (ret != LDB_SUCCESS) {
-                               return ret;
-                       }
-               }
-
-               return handle->status;
-       }
-
-       return paged_wait_once(handle);
 }
 
 static int paged_request_init(struct ldb_module *module)
 {
        struct private_data *data;
-       struct ldb_request *req;
        int ret;
 
        data = talloc(module, struct private_data);
        if (data == NULL) {
                return LDB_ERR_OTHER;
        }
-       
+
        data->next_free_id = 1;
        data->store = NULL;
        module->private_data = data;
 
-       req = talloc(module, struct ldb_request);
-       if (req == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       req->operation = LDB_REQ_REGISTER_CONTROL;
-       req->op.reg_control.oid = LDB_CONTROL_PAGED_RESULTS_OID;
-       req->controls = NULL;
-
-       ret = ldb_request(module->ldb, req);
+       ret = ldb_mod_register_control(module, LDB_CONTROL_PAGED_RESULTS_OID);
        if (ret != LDB_SUCCESS) {
-               ldb_debug(module->ldb, LDB_DEBUG_WARNING, "paged_request: Unable to register control with rootdse!\n");
+               ldb_debug(module->ldb, LDB_DEBUG_WARNING,
+                       "paged_request:"
+                       "Unable to register control with rootdse!\n");
        }
 
-       talloc_free(req);
        return ldb_next_init(module);
 }
 
 const struct ldb_module_ops ldb_paged_results_module_ops = {
        .name           = "paged_results",
        .search         = paged_search,
-       .wait           = paged_wait,
        .init_context   = paged_request_init
 };
index 40e87f70d60c83e124a5e7ae0877d941c6102c67..7a728e3bb0e3d090140a2cbaa919630e7ce3f496 100644 (file)
@@ -1,7 +1,7 @@
 /* 
    ldb database library
 
-   Copyright (C) Simo Sorce  2005-2006
+   Copyright (C) Simo Sorce  2005-2008
 
      ** NOTE! The following LGPL license applies to the ldb
      ** library. This does NOT imply that all of Samba is released
@@ -46,12 +46,7 @@ struct private_data {
 
 struct ps_context {
        struct ldb_module *module;
-       void *up_context;
-       int (*up_callback)(struct ldb_context *, void *, struct ldb_reply *);
-
-       struct ldb_request *orig_req;
-
-       struct ldb_request *new_req;
+       struct ldb_request *req;
 
        bool pending;
 
@@ -59,51 +54,13 @@ struct ps_context {
        int num_referrals;
 };
 
-static struct ldb_handle *init_handle(void *mem_ctx, struct ldb_module *module,
-                                           void *context,
-                                           int (*callback)(struct ldb_context *, void *, struct ldb_reply *))
+static int check_ps_continuation(struct ldb_request *req, struct ldb_reply *ares)
 {
        struct ps_context *ac;
-       struct ldb_handle *h;
-
-       h = talloc_zero(mem_ctx, struct ldb_handle);
-       if (h == NULL) {
-               ldb_set_errstring(module->ldb, "Out of Memory");
-               return NULL;
-       }
-
-       h->module = module;
-
-       ac = talloc_zero(h, struct ps_context);
-       if (ac == NULL) {
-               ldb_set_errstring(module->ldb, "Out of Memory");
-               talloc_free(h);
-               return NULL;
-       }
-
-       h->private_data = (void *)ac;
-
-       h->state = LDB_ASYNC_INIT;
-       h->status = LDB_SUCCESS;
-
-       ac->module = module;
-       ac->up_context = context;
-       ac->up_callback = callback;
-
-       ac->pending = false;
-
-
-
-       ac->saved_referrals = NULL;
-       ac->num_referrals = 0;
-
-       return h;
-}
-
-static int check_ps_continuation(struct ldb_reply *ares, struct ps_context *ac)
-{
        struct ldb_paged_control *rep_control, *req_control;
 
+       ac = talloc_get_type(req->context, struct ps_context);
+
        /* look up our paged control */
        if (!ares->controls || strcmp(LDB_CONTROL_PAGED_RESULTS_OID, ares->controls[0]->oid) != 0) {
                /* something wrong here */
@@ -122,12 +79,12 @@ static int check_ps_continuation(struct ldb_reply *ares, struct ps_context *ac)
        /* if there's a reply control we must find a request
         * control matching it */
 
-       if (strcmp(LDB_CONTROL_PAGED_RESULTS_OID, ac->new_req->controls[0]->oid) != 0) {
+       if (strcmp(LDB_CONTROL_PAGED_RESULTS_OID, req->controls[0]->oid) != 0) {
                /* something wrong here */
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       req_control = talloc_get_type(ac->new_req->controls[0]->data, struct ldb_paged_control);
+       req_control = talloc_get_type(req->controls[0]->data, struct ldb_paged_control);
 
        if (req_control->cookie) {
                talloc_free(req_control->cookie);
@@ -142,7 +99,7 @@ static int check_ps_continuation(struct ldb_reply *ares, struct ps_context *ac)
        return LDB_SUCCESS;
 }
 
-static int store_referral(char *referral, struct ps_context *ac)
+static int store_referral(struct ps_context *ac, char *referral)
 {
        ac->saved_referrals = talloc_realloc(ac, ac->saved_referrals, char *, ac->num_referrals + 2);
        if (!ac->saved_referrals) {
@@ -160,13 +117,14 @@ static int store_referral(char *referral, struct ps_context *ac)
        return LDB_SUCCESS;
 }
 
-static int send_referrals(struct ldb_context *ldb, struct ps_context *ac)
+static int send_referrals(struct ps_context *ac)
 {
        struct ldb_reply *ares;
+       int ret;
        int i;
 
        for (i = 0; i < ac->num_referrals; i++) {
-               ares = talloc_zero(ac, struct ldb_reply);
+               ares = talloc_zero(ac->req, struct ldb_reply);
                if (!ares) {
                        return LDB_ERR_OPERATIONS_ERROR;
                }
@@ -174,69 +132,87 @@ static int send_referrals(struct ldb_context *ldb, struct ps_context *ac)
                ares->type = LDB_REPLY_REFERRAL;
                ares->referral = ac->saved_referrals[i];
 
-               ac->up_callback(ldb, ac->up_context, ares);
+               ret = ldb_module_send_referral(ac->req, ares->referral);
+               if (ret != LDB_SUCCESS) {
+                       return ret;
+               }
        }
 
        return LDB_SUCCESS;
 }
 
-static int ps_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares)
+static int ps_next_request(struct ps_context *ac);
+
+static int ps_callback(struct ldb_request *req, struct ldb_reply *ares)
 {
-       struct ps_context *ac = NULL;
-       int ret = LDB_ERR_OPERATIONS_ERROR;
+       struct ps_context *ac;
+       int ret;
 
-       if (!context || !ares) {
-               ldb_set_errstring(ldb, "NULL Context or Result in callback");
-               goto error;
-       }
+       ac = talloc_get_type(req->context, struct ps_context);
 
-       ac = talloc_get_type(context, struct ps_context);
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
 
        switch (ares->type) {
        case LDB_REPLY_ENTRY:
-               ac->up_callback(ldb, ac->up_context, ares);
+               ret = ldb_module_send_entry(ac->req, ares->message);
+               if (ret != LDB_SUCCESS) {
+                       return ldb_module_done(ac->req, NULL, NULL, ret);
+               }
                break;
 
        case LDB_REPLY_REFERRAL:
-               ret = store_referral(ares->referral, ac);
+               ret = store_referral(ac, ares->referral);
                if (ret != LDB_SUCCESS) {
-                       goto error;
+                       return ldb_module_done(ac->req, NULL, NULL, ret);
                }
                break;
 
        case LDB_REPLY_DONE:
-               ret = check_ps_continuation(ares, ac);
+
+               ret = check_ps_continuation(req, ares);
                if (ret != LDB_SUCCESS) {
-                       goto error;
+                       return ldb_module_done(ac->req, NULL, NULL, ret);
                }
-               if (!ac->pending) {
+
+               if (ac->pending) {
+
+                       ret = ps_next_request(ac);
+                       if (ret != LDB_SUCCESS) {
+                               return ldb_module_done(ac->req,
+                                                       NULL, NULL, ret);
+                       }
+
+               } else {
+
                        /* send referrals */
-                       ret = send_referrals(ldb, ac);
+                       ret = send_referrals(ac);
                        if (ret != LDB_SUCCESS) {
-                               goto error;
+                               return ldb_module_done(ac->req,
+                                                       NULL, NULL, ret);
                        }
 
                        /* send REPLY_DONE */
-                       ac->up_callback(ldb, ac->up_context, ares);
+                       return ldb_module_done(ac->req, ares->controls,
+                                               ares->response, LDB_SUCCESS);
                }
                break;
-       default:
-               goto error;
        }
 
-       return LDB_SUCCESS;
-
-error:
        talloc_free(ares);
-       return ret;
+       return LDB_SUCCESS;
 }
 
 static int ps_search(struct ldb_module *module, struct ldb_request *req)
 {
        struct private_data *private_data;
-       struct ldb_paged_control *control;
        struct ps_context *ac;
-       struct ldb_handle *h;
 
        private_data = talloc_get_type(module->private_data, struct private_data);
 
@@ -248,216 +224,151 @@ static int ps_search(struct ldb_module *module, struct ldb_request *req)
                return ldb_next_request(module, req);
        }
 
-       if (!req->callback || !req->context) {
-               ldb_set_errstring(module->ldb,
-                                 "Async interface called with NULL callback function or NULL context");
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-       
-       h = init_handle(req, module, req->context, req->callback);
-       if (!h) {
+       ac = talloc_zero(req, struct ps_context);
+       if (ac == NULL) {
+               ldb_oom(module->ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       ac = talloc_get_type(h->private_data, struct ps_context);
-
-       ac->new_req = talloc(ac, struct ldb_request);
-       if (!ac->new_req) return LDB_ERR_OPERATIONS_ERROR;
-
-       ac->new_req->controls = talloc_array(ac->new_req, struct ldb_control *, 2);
-       if (!ac->new_req->controls) return LDB_ERR_OPERATIONS_ERROR;
-
-       ac->new_req->controls[0] = talloc(ac->new_req->controls, struct ldb_control);
-       if (!ac->new_req->controls[0]) return LDB_ERR_OPERATIONS_ERROR;
-
-       control = talloc(ac->new_req->controls[0], struct ldb_paged_control);
-       if (!control) return LDB_ERR_OPERATIONS_ERROR;
-
-       control->size = PS_DEFAULT_PAGE_SIZE;
-       control->cookie = NULL;
-       control->cookie_len = 0;
-
-       ac->new_req->controls[0]->oid = LDB_CONTROL_PAGED_RESULTS_OID;
-       ac->new_req->controls[0]->critical = 1;
-       ac->new_req->controls[0]->data = control;
-
-       ac->new_req->controls[1] = NULL;
 
-       ac->new_req->operation = req->operation;
-       ac->new_req->op.search.base = req->op.search.base;
-       ac->new_req->op.search.scope = req->op.search.scope;
-       ac->new_req->op.search.tree = req->op.search.tree;
-       ac->new_req->op.search.attrs = req->op.search.attrs;
-       ac->new_req->context = ac;
-       ac->new_req->callback = ps_callback;
-       ldb_set_timeout_from_prev_req(module->ldb, req, ac->new_req);
-
-       req->handle = h;
+       ac->module = module;
+       ac->req = req;
+       ac->pending = false;
+       ac->saved_referrals = NULL;
+       ac->num_referrals = 0;
 
-       return ldb_next_request(module, ac->new_req);
+       return ps_next_request(ac);
 }
 
-static int ps_continuation(struct ldb_handle *handle)
-{
-       struct ps_context *ac;
+static int ps_next_request(struct ps_context *ac) {
 
-       if (!handle || !handle->private_data) {
+       struct ldb_paged_control *control;
+       struct ldb_control **controls;
+       struct ldb_request *new_req;
+       int ret;
+
+       controls = talloc_array(ac, struct ldb_control *, 2);
+       if (!controls) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       ac = talloc_get_type(handle->private_data, struct ps_context);
-
-       /* reset the requests handle */
-       ac->new_req->handle = NULL;
-
-       return ldb_next_request(handle->module, ac->new_req);
-}
-
-static int ps_wait_once(struct ldb_handle *handle)
-{
-       struct ps_context *ac;
-       int ret;
-    
-       if (!handle || !handle->private_data) {
+       controls[0] = talloc(controls, struct ldb_control);
+       if (!controls[0]) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       if (handle->state == LDB_ASYNC_DONE) {
-               return handle->status;
+       control = talloc(controls[0], struct ldb_paged_control);
+       if (!control) {
+               return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       handle->state = LDB_ASYNC_PENDING;
-       handle->status = LDB_SUCCESS;
-
-       ac = talloc_get_type(handle->private_data, struct ps_context);
-
-       ret = ldb_wait(ac->new_req->handle, LDB_WAIT_NONE);
+       control->size = PS_DEFAULT_PAGE_SIZE;
+       control->cookie = NULL;
+       control->cookie_len = 0;
 
+       controls[0]->oid = LDB_CONTROL_PAGED_RESULTS_OID;
+       controls[0]->critical = 1;
+       controls[0]->data = control;
+       controls[1] = NULL;
+
+       ret = ldb_build_search_req_ex(&new_req, ac->module->ldb, ac,
+                                       ac->req->op.search.base,
+                                       ac->req->op.search.scope,
+                                       ac->req->op.search.tree,
+                                       ac->req->op.search.attrs,
+                                       controls,
+                                       ac,
+                                       ps_callback,
+                                       ac->req);
        if (ret != LDB_SUCCESS) {
-               handle->status = ret;
-               goto done;
-       }
-
-       if (ac->new_req->handle->status != LDB_SUCCESS) {
-               handle->status = ac->new_req->handle->status;
-               goto done;
-       }
-
-       if (ac->new_req->handle->state != LDB_ASYNC_DONE) {
-               return LDB_SUCCESS;
-       } 
-
-       /* see if we need to send another request for the next batch */
-       if (ac->pending) {
-               ret = ps_continuation(handle);
-               if (ret != LDB_SUCCESS) {
-                       handle->status = ret;
-                       goto done;
-               }
-
-               /* continue the search with the next request */
-               return LDB_SUCCESS;
+               return ret;
        }
+       talloc_steal(new_req, controls);
 
-       ret = LDB_SUCCESS;
-
-done:
-       handle->state = LDB_ASYNC_DONE;
-       return ret;
+       return ldb_next_request(ac->module, new_req);
 }
 
-static int ps_wait(struct ldb_handle *handle, enum ldb_wait_type type)
+static int check_supported_paged(struct ldb_request *req,
+                                struct ldb_reply *ares)
 {
-       int ret;
-
-       if (!handle || !handle->private_data) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
+       struct private_data *data;
 
-       if (type == LDB_WAIT_ALL) {
-               while (handle->state != LDB_ASYNC_DONE) {
-                       ret = ps_wait_once(handle);
-                       if (ret != LDB_SUCCESS) {
-                               return ret;
-                       }
-               }
+       data = talloc_get_type(req->context, struct private_data);
 
-               return handle->status;
+       if (!ares) {
+               return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
        }
-       return ps_wait_once(handle);
-}
 
-static int check_supported_paged(struct ldb_context *ldb, void *context, 
-                                struct ldb_reply *ares) 
-{
-       struct private_data *data;
-       data = talloc_get_type(context,
-                              struct private_data);
-       if (ares->type == LDB_REPLY_ENTRY) {
+       switch (ares->type) {
+       case LDB_REPLY_ENTRY:
                if (ldb_msg_check_string_attribute(ares->message,
                                                   "supportedControl",
                                                   LDB_CONTROL_PAGED_RESULTS_OID)) {
                        data->paged_supported = true;
                }
+               break;
+
+       case LDB_REPLY_REFERRAL:
+               /* ignore */
+               break;
+
+       case LDB_REPLY_DONE:
+               return ldb_request_done(req, LDB_SUCCESS);
        }
+
+       talloc_free(ares);
        return LDB_SUCCESS;
 }
 
-
 static int ps_init(struct ldb_module *module)
 {
        static const char *attrs[] = { "supportedControl", NULL };
        struct private_data *data;
+       struct ldb_dn *base;
        int ret;
        struct ldb_request *req;
 
        data = talloc(module, struct private_data);
        if (data == NULL) {
-               ldb_set_errstring(module->ldb, "Out of Memory");
-               return LDB_ERR_OTHER;
+               ldb_oom(module->ldb);
+               return LDB_ERR_OPERATIONS_ERROR;
        }
        module->private_data = data;
        data->paged_supported = false;
 
-       req = talloc(module, struct ldb_request);
-       if (req == NULL) {
-               ldb_set_errstring(module->ldb, "Out of Memory");
+       base = ldb_dn_new(module, module->ldb, "");
+       if (base == NULL) {
+               ldb_oom(module->ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
-
-       req->operation = LDB_SEARCH;
-       req->op.search.base = ldb_dn_new(req, module->ldb, "");
-       req->op.search.scope = LDB_SCOPE_BASE;
-
-       req->op.search.tree = ldb_parse_tree(req, "objectClass=*");
-       if (req->op.search.tree == NULL) {
-               ldb_set_errstring(module->ldb, "Unable to parse search expression");
-               talloc_free(req);
-               return LDB_ERR_OPERATIONS_ERROR;
+       ret = ldb_build_search_req(&req, module->ldb, module,
+                                  base, LDB_SCOPE_BASE,
+                                  "(objectClass=*)",
+                                  attrs, NULL,
+                                  data, check_supported_paged,
+                                  NULL);
+       if (ret != LDB_SUCCESS) {
+               return ret;
        }
 
-       req->op.search.attrs = attrs;
-       req->controls = NULL;
-       req->context = data;
-       req->callback = check_supported_paged;
-       ldb_set_timeout(module->ldb, req, 0); /* use default timeout */
-
        ret = ldb_next_request(module, req);
-       
        if (ret == LDB_SUCCESS) {
                ret = ldb_wait(req->handle, LDB_WAIT_ALL);
        }
-       
-       talloc_free(req);
        if (ret != LDB_SUCCESS) {
                return ret;
        }
 
+       talloc_free(base);
+       talloc_free(req);
+
        return ldb_next_init(module);
 }
 
 _PUBLIC_ const struct ldb_module_ops ldb_paged_searches_module_ops = {
        .name           = "paged_searches",
        .search         = ps_search,
-       .wait           = ps_wait,
        .init_context   = ps_init
 };
index 65c044c0f4127c2ef0cf230854904adbc69660e2..62b8ce5112c1f6ef13a404b481f0fccff8bcef5a 100644 (file)
@@ -2,7 +2,7 @@
    ldb database library
 
    Copyright (C) Andrew Bartlet 2005
-   Copyright (C) Simo Sorce     2006
+   Copyright (C) Simo Sorce     2006-2008
 
      ** NOTE! The following LGPL license applies to the ldb
      ** library. This does NOT imply that all of Samba is released
 
 #include "ldb_includes.h"
 
+struct rename_context {
+
+       struct ldb_module *module;
+       struct ldb_request *req;
+
+       struct ldb_reply *ares;
+};
+
 static struct ldb_message_element *rdn_name_find_attribute(const struct ldb_message *msg, const char *name)
 {
        int i;
@@ -51,11 +59,38 @@ static struct ldb_message_element *rdn_name_find_attribute(const struct ldb_mess
        return NULL;
 }
 
+static int rdn_name_add_callback(struct ldb_request *req,
+                                struct ldb_reply *ares)
+{
+       struct rename_context *ac;
+
+       ac = talloc_get_type(req->context, struct rename_context);
+
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
+
+       if (ares->type != LDB_REPLY_DONE) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+
+       return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, LDB_SUCCESS);
+}
+
 static int rdn_name_add(struct ldb_module *module, struct ldb_request *req)
 {
        struct ldb_request *down_req;
+       struct rename_context *ac;
        struct ldb_message *msg;
        struct ldb_message_element *attribute;
+       const struct ldb_schema_attribute *a;
        const char *rdn_name;
        struct ldb_val rdn_val;
        int i, ret;
@@ -67,21 +102,22 @@ static int rdn_name_add(struct ldb_module *module, struct ldb_request *req)
                return ldb_next_request(module, req);
        }
 
-       down_req = talloc(req, struct ldb_request);
-       if (down_req == NULL) {
+       ac = talloc_zero(req, struct rename_context);
+       if (ac == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       *down_req = *req;
+       ac->module = module;
+       ac->req = req;
 
-       down_req->op.add.message = msg = ldb_msg_copy_shallow(down_req, req->op.add.message);
+       msg = ldb_msg_copy_shallow(req, req->op.add.message);
        if (msg == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
        rdn_name = ldb_dn_get_rdn_name(msg->dn);
        if (rdn_name == NULL) {
-               talloc_free(down_req);
+               talloc_free(ac);
                return LDB_ERR_OPERATIONS_ERROR;
        }
        
@@ -93,7 +129,7 @@ static int rdn_name_add(struct ldb_module *module, struct ldb_request *req)
        }
 
        if (ldb_msg_add_value(msg, "name", &rdn_val, NULL) != 0) {
-               talloc_free(down_req);
+               talloc_free(ac);
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
@@ -101,14 +137,16 @@ static int rdn_name_add(struct ldb_module *module, struct ldb_request *req)
 
        if (!attribute) {
                if (ldb_msg_add_value(msg, rdn_name, &rdn_val, NULL) != 0) {
-                       talloc_free(down_req);
+                       talloc_free(ac);
                        return LDB_ERR_OPERATIONS_ERROR;
                }
        } else {
-               const struct ldb_schema_attribute *a = ldb_schema_attribute_by_name(module->ldb, rdn_name);
+               a = ldb_schema_attribute_by_name(module->ldb, rdn_name);
 
                for (i = 0; i < attribute->num_values; i++) {
-                       if (a->syntax->comparison_fn(module->ldb, msg, &rdn_val, &attribute->values[i]) == 0) {
+                       ret = a->syntax->comparison_fn(module->ldb, msg,
+                                       &rdn_val, &attribute->values[i]);
+                       if (ret == 0) {
                                /* overwrite so it matches in case */
                                attribute->values[i] = rdn_val;
                                break;
@@ -118,218 +156,166 @@ static int rdn_name_add(struct ldb_module *module, struct ldb_request *req)
                        ldb_debug_set(module->ldb, LDB_DEBUG_FATAL, 
                                      "RDN mismatch on %s: %s (%s)", 
                                      ldb_dn_get_linearized(msg->dn), rdn_name, rdn_val.data);
-                       talloc_free(down_req);
+                       talloc_free(ac);
                        /* Match AD's error here */
                        return LDB_ERR_INVALID_DN_SYNTAX;
                }
        }
 
-       /* go on with the call chain */
-       ret = ldb_next_request(module, down_req);
-
-       /* do not free down_req as the call results may be linked to it,
-        * it will be freed when the upper level request get freed */
-       if (ret == LDB_SUCCESS) {
-               req->handle = down_req->handle;
+       ret = ldb_build_add_req(&down_req, module->ldb, req,
+                               msg,
+                               req->controls,
+                               ac, rdn_name_add_callback,
+                               req);
+       if (ret != LDB_SUCCESS) {
+               return ret;
        }
 
-       return ret;
-}
-
-struct rename_context {
+       talloc_steal(down_req, msg);
 
-       enum {RENAME_RENAME, RENAME_MODIFY} step;
-       struct ldb_request *orig_req;
-       struct ldb_request *down_req;
-       struct ldb_request *mod_req;
-};
+       /* go on with the call chain */
+       return ldb_next_request(module, down_req);
+}
 
-static int rdn_name_rename(struct ldb_module *module, struct ldb_request *req)
+static int rdn_modify_callback(struct ldb_request *req, struct ldb_reply *ares)
 {
-       struct ldb_handle *h;
        struct rename_context *ac;
 
-       ldb_debug(module->ldb, LDB_DEBUG_TRACE, "rdn_name_rename\n");
+       ac = talloc_get_type(req->context, struct rename_context);
 
-       /* do not manipulate our control entries */
-       if (ldb_dn_is_special(req->op.rename.newdn)) {
-               return ldb_next_request(module, req);
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
        }
-
-       h = talloc_zero(req, struct ldb_handle);
-       if (h == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
        }
 
-       h->module = module;
-
-       ac = talloc_zero(h, struct rename_context);
-       if (ac == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
+       /* the only supported reply right now is a LDB_REPLY_DONE */
+       if (ares->type != LDB_REPLY_DONE) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
        }
 
-       h->private_data = (void *)ac;
-
-       h->state = LDB_ASYNC_INIT;
-       h->status = LDB_SUCCESS;
-
-       ac->orig_req = req;
-       ac->down_req = talloc(req, struct ldb_request);
-       if (ac->down_req == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       *(ac->down_req) = *req;
-
-       ac->step = RENAME_RENAME;
-
-       req->handle = h;
-
-       /* rename first, modify "name" if rename is ok */
-       return ldb_next_request(module, ac->down_req);
+       /* send saved controls eventually */
+       return ldb_module_done(ac->req, ac->ares->controls,
+                               ac->ares->response, LDB_SUCCESS);
 }
 
-static int rdn_name_rename_do_mod(struct ldb_handle *h) {
-
+static int rdn_rename_callback(struct ldb_request *req, struct ldb_reply *ares)
+{
        struct rename_context *ac;
+       struct ldb_request *mod_req;
        const char *rdn_name;
        struct ldb_val rdn_val;
        struct ldb_message *msg;
+       int ret;
 
-       ac = talloc_get_type(h->private_data, struct rename_context);
+       ac = talloc_get_type(req->context, struct rename_context);
 
-       ac->mod_req = talloc_zero(ac, struct ldb_request);
+       if (!ares) {
+               goto error;
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
 
-       ac->mod_req->operation = LDB_MODIFY;
-       ac->mod_req->op.mod.message = msg = ldb_msg_new(ac->mod_req);
-       if (msg == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
+       /* the only supported reply right now is a LDB_REPLY_DONE */
+       if (ares->type != LDB_REPLY_DONE) {
+               goto error;
        }
 
-       msg->dn = ldb_dn_copy(msg, ac->orig_req->op.rename.newdn);
+       /* save reply for caller */
+       ac->ares = talloc_steal(ac, ares);
+
+       msg = ldb_msg_new(ac);
+       if (msg == NULL) {
+               goto error;
+       }
+       msg->dn = ldb_dn_copy(msg, ac->req->op.rename.newdn);
        if (msg->dn == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
+               goto error;
        }
-
-       rdn_name = ldb_dn_get_rdn_name(ac->orig_req->op.rename.newdn);
+       rdn_name = ldb_dn_get_rdn_name(ac->req->op.rename.newdn);
        if (rdn_name == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
+               goto error;
        }
        
-       rdn_val = ldb_val_dup(msg, ldb_dn_get_rdn_val(ac->orig_req->op.rename.newdn));
+       rdn_val = ldb_val_dup(msg, ldb_dn_get_rdn_val(ac->req->op.rename.newdn));
        
        if (ldb_msg_add_empty(msg, rdn_name, LDB_FLAG_MOD_REPLACE, NULL) != 0) {
-               return LDB_ERR_OPERATIONS_ERROR;
+               goto error;
        }
        if (ldb_msg_add_value(msg, rdn_name, &rdn_val, NULL) != 0) {
-               return LDB_ERR_OPERATIONS_ERROR;
+               goto error;
        }
        if (ldb_msg_add_empty(msg, "name", LDB_FLAG_MOD_REPLACE, NULL) != 0) {
-               return LDB_ERR_OPERATIONS_ERROR;
+               goto error;
        }
        if (ldb_msg_add_value(msg, "name", &rdn_val, NULL) != 0) {
-               return LDB_ERR_OPERATIONS_ERROR;
+               goto error;
        }
 
-       ldb_set_timeout_from_prev_req(h->module->ldb, ac->orig_req, ac->mod_req);
-
-       ac->step = RENAME_MODIFY;
+       ret = ldb_build_mod_req(&mod_req, ac->module->ldb,
+                               ac, msg, NULL,
+                               ac, rdn_modify_callback,
+                               req);
+       if (ret != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, NULL, NULL, ret);
+       }
+       talloc_steal(mod_req, msg);
 
        /* do the mod call */
-       return ldb_request(h->module->ldb, ac->mod_req);
+       return ldb_request(ac->module->ldb, mod_req);
+
+error:
+       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
 }
 
-static int rdn_name_wait_once(struct ldb_handle *handle)
+static int rdn_name_rename(struct ldb_module *module, struct ldb_request *req)
 {
        struct rename_context *ac;
+       struct ldb_request *down_req;
        int ret;
-    
-       if (!handle || !handle->private_data) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       if (handle->state == LDB_ASYNC_DONE) {
-               return handle->status;
-       }
 
-       handle->state = LDB_ASYNC_PENDING;
-       handle->status = LDB_SUCCESS;
-
-       ac = talloc_get_type(handle->private_data, struct rename_context);
-
-       switch(ac->step) {
-       case RENAME_RENAME:
-               ret = ldb_wait(ac->down_req->handle, LDB_WAIT_NONE);
-               if (ret != LDB_SUCCESS) {
-                       handle->status = ret;
-                       goto done;
-               }
-               if (ac->down_req->handle->status != LDB_SUCCESS) {
-                       handle->status = ac->down_req->handle->status;
-                       goto done;
-               }
-
-               if (ac->down_req->handle->state != LDB_ASYNC_DONE) {
-                       return LDB_SUCCESS;
-               }
-
-               /* rename operation done */
-               return rdn_name_rename_do_mod(handle);
-
-       case RENAME_MODIFY:
-               ret = ldb_wait(ac->mod_req->handle, LDB_WAIT_NONE);
-               if (ret != LDB_SUCCESS) {
-                       handle->status = ret;
-                       goto done;
-               }
-               if (ac->mod_req->handle->status != LDB_SUCCESS) {
-                       handle->status = ac->mod_req->handle->status;
-                       goto done;
-               }
-
-               if (ac->mod_req->handle->state != LDB_ASYNC_DONE) {
-                       return LDB_SUCCESS;
-               }
-
-               break;
+       ldb_debug(module->ldb, LDB_DEBUG_TRACE, "rdn_name_rename\n");
 
-       default:
-               ret = LDB_ERR_OPERATIONS_ERROR;
-               goto done;
+       /* do not manipulate our control entries */
+       if (ldb_dn_is_special(req->op.rename.newdn)) {
+               return ldb_next_request(module, req);
        }
 
-       ret = LDB_SUCCESS;
-
-done:
-       handle->state = LDB_ASYNC_DONE;
-       return ret;
-}
-
-static int rdn_name_wait(struct ldb_handle *handle, enum ldb_wait_type type)
-{
-       int ret;
-       if (!handle || !handle->private_data) {
+       ac = talloc_zero(req, struct rename_context);
+       if (ac == NULL) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       if (type == LDB_WAIT_ALL) {
-               while (handle->state != LDB_ASYNC_DONE) {
-                       ret = rdn_name_wait_once(handle);
-                       if (ret != LDB_SUCCESS) {
-                               return ret;
-                       }
-               }
+       ac->module = module;
+       ac->req = req;
 
-               return handle->status;
+       ret = ldb_build_rename_req(&down_req,
+                                  module->ldb,
+                                  ac,
+                                  req->op.rename.olddn,
+                                  req->op.rename.newdn,
+                                  req->controls,
+                                  ac,
+                                  rdn_rename_callback,
+                                  req);
+
+       if (ret != LDB_SUCCESS) {
+               return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       return rdn_name_wait_once(handle);
+       /* rename first, modify "name" if rename is ok */
+       return ldb_next_request(module, down_req);
 }
 
 const struct ldb_module_ops ldb_rdn_name_module_ops = {
        .name              = "rdn_name",
        .add               = rdn_name_add,
        .rename            = rdn_name_rename,
-       .wait              = rdn_name_wait
 };
index 746befa559208bb368a0a4bf875d5eb46b617da8..64d60f370cf7111099bfcf3f95b1dfbc64c86e77 100644 (file)
@@ -1,7 +1,7 @@
 /* 
    ldb database library
 
-   Copyright (C) Simo Sorce  2005
+   Copyright (C) Simo Sorce  2005-2008
 
      ** NOTE! The following LGPL license applies to the ldb
      ** library. This does NOT imply that all of Samba is released
@@ -43,8 +43,6 @@ struct opaque {
 
 struct sort_context {
        struct ldb_module *module;
-       void *up_context;
-       int (*up_callback)(struct ldb_context *, void *, struct ldb_reply *);
 
        char *attributeName;
        char *orderingRule;
@@ -53,7 +51,6 @@ struct sort_context {
        struct ldb_request *req;
        struct ldb_message **msgs;
        char **referrals;
-       struct ldb_control **controls;
        int num_msgs;
        int num_refs;
 
@@ -61,40 +58,6 @@ struct sort_context {
        int sort_result;
 };
 
-static struct ldb_handle *init_handle(void *mem_ctx, struct ldb_module *module,
-                                           void *context,
-                                           int (*callback)(struct ldb_context *, void *, struct ldb_reply *))
-{
-       struct sort_context *ac;
-       struct ldb_handle *h;
-
-       h = talloc_zero(mem_ctx, struct ldb_handle);
-       if (h == NULL) {
-               ldb_set_errstring(module->ldb, "Out of Memory");
-               return NULL;
-       }
-
-       h->module = module;
-
-       ac = talloc_zero(h, struct sort_context);
-       if (ac == NULL) {
-               ldb_set_errstring(module->ldb, "Out of Memory");
-               talloc_free(h);
-               return NULL;
-       }
-
-       h->private_data = (void *)ac;
-
-       h->state = LDB_ASYNC_INIT;
-       h->status = LDB_SUCCESS;
-
-       ac->module = module;
-       ac->up_context = context;
-       ac->up_callback = callback;
-
-       return h;
-}
-
 static int build_response(void *mem_ctx, struct ldb_control ***ctrls, int result, const char *desc)
 {
        struct ldb_control **controls;
@@ -142,7 +105,7 @@ static int sort_compare(struct ldb_message **msg1, struct ldb_message **msg2, vo
        struct sort_context *ac = talloc_get_type(opaque, struct sort_context);
        struct ldb_message_element *el1, *el2;
 
-       if (ac->sort_result != 0) {
+       if (!ac || ac->sort_result != 0) {
                /* an error occurred previously,
                 * let's exit the sorting by returning always 0 */
                return 0;
@@ -154,7 +117,7 @@ static int sort_compare(struct ldb_message **msg1, struct ldb_message **msg2, vo
        if (!el1 || !el2) {
                /* the attribute was not found return and
                 * set an error */
-               ac->sort_result = 53;
+               ac->sort_result = LDB_ERR_UNWILLING_TO_PERFORM;
                return 0;
        }
 
@@ -164,51 +127,111 @@ static int sort_compare(struct ldb_message **msg1, struct ldb_message **msg2, vo
        return ac->a->syntax->comparison_fn(ac->module->ldb, ac, &el1->values[0], &el2->values[0]);
 }
 
-static int server_sort_search_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares)
+static int server_sort_results(struct sort_context *ac)
 {
-       struct sort_context *ac = NULL;
-       
-       if (!context || !ares) {
-               ldb_set_errstring(ldb, "NULL Context or Result in callback");
-               goto error;
-       }       
+       struct ldb_reply *ares;
+       int i, ret;
+
+       ac->a = ldb_schema_attribute_by_name(ac->module->ldb, ac->attributeName);
+       ac->sort_result = 0;
+
+       ldb_qsort(ac->msgs, ac->num_msgs,
+                 sizeof(struct ldb_message *),
+                 ac, (ldb_qsort_cmp_fn_t)sort_compare);
+
+       if (ac->sort_result != LDB_SUCCESS) {
+               return ac->sort_result;
+       }
+
+       for (i = 0; i < ac->num_msgs; i++) {
+               ares = talloc_zero(ac, struct ldb_reply);
+               if (!ares) {
+                       return LDB_ERR_OPERATIONS_ERROR;
+               }
+
+               ares->type = LDB_REPLY_ENTRY;
+               ares->message = talloc_move(ares, &ac->msgs[i]);
+
+               ret = ldb_module_send_entry(ac->req, ares->message);
+               if (ret != LDB_SUCCESS) {
+                       return ret;
+               }
+       }
+
+       for (i = 0; i < ac->num_refs; i++) {
+               ares = talloc_zero(ac, struct ldb_reply);
+               if (!ares) {
+                       return LDB_ERR_OPERATIONS_ERROR;
+               }
+
+               ares->type = LDB_REPLY_REFERRAL;
+               ares->referral = talloc_move(ares, &ac->referrals[i]);
+
+               ret = ldb_module_send_referral(ac->req, ares->referral);
+               if (ret != LDB_SUCCESS) {
+                       return ret;
+               }
+       }
+
+       return LDB_SUCCESS;
+}
+
+static int server_sort_search_callback(struct ldb_request *req, struct ldb_reply *ares)
+{
+       struct sort_context *ac;
+       int ret;
 
-               ac = talloc_get_type(context, struct sort_context);
+       ac = talloc_get_type(req->context, struct sort_context);
 
-       if (ares->type == LDB_REPLY_ENTRY) {
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
+
+       switch (ares->type) {
+       case LDB_REPLY_ENTRY:
                ac->msgs = talloc_realloc(ac, ac->msgs, struct ldb_message *, ac->num_msgs + 2);
                if (! ac->msgs) {
-                       goto error;
+                       talloc_free(ares);
+                       ldb_oom(ac->module->ldb);
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
                }
 
-               ac->msgs[ac->num_msgs + 1] = NULL;
-
-               ac->msgs[ac->num_msgs] = talloc_move(ac->msgs, &ares->message);
+               ac->msgs[ac->num_msgs] = talloc_steal(ac->msgs, ares->message);
                ac->num_msgs++;
-       }
+               ac->msgs[ac->num_msgs] = NULL;
 
-       if (ares->type == LDB_REPLY_REFERRAL) {
+               break;
+
+       case LDB_REPLY_REFERRAL:
                ac->referrals = talloc_realloc(ac, ac->referrals, char *, ac->num_refs + 2);
                if (! ac->referrals) {
-                       goto error;
+                       talloc_free(ares);
+                       ldb_oom(ac->module->ldb);
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
                }
 
-               ac->referrals[ac->num_refs + 1] = NULL;
-               ac->referrals[ac->num_refs] = talloc_move(ac->referrals, &ares->referral);
-
+               ac->referrals[ac->num_refs] = talloc_steal(ac->referrals, ares->referral);
                ac->num_refs++;
-       }
+               ac->referrals[ac->num_refs] = NULL;
 
-       if (ares->type == LDB_REPLY_DONE) {
-               ac->controls = talloc_move(ac, &ares->controls);
+               break;
+
+       case LDB_REPLY_DONE:
+
+               ret = server_sort_results(ac);
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ret);
        }
 
        talloc_free(ares);
        return LDB_SUCCESS;
-
-error:
-       talloc_free(ares);
-       return LDB_ERR_OPERATIONS_ERROR;
 }
 
 static int server_sort_search(struct ldb_module *module, struct ldb_request *req)
@@ -216,8 +239,9 @@ static int server_sort_search(struct ldb_module *module, struct ldb_request *req
        struct ldb_control *control;
        struct ldb_server_sort_control **sort_ctrls;
        struct ldb_control **saved_controls;
+       struct ldb_control **controls;
+       struct ldb_request *down_req;
        struct sort_context *ac;
-       struct ldb_handle *h;
        int ret;
 
        /* check if there's a paged request control */
@@ -227,19 +251,14 @@ static int server_sort_search(struct ldb_module *module, struct ldb_request *req
                return ldb_next_request(module, req);
        }
 
-       req->handle = NULL;
-
-       if (!req->callback || !req->context) {
-               ldb_set_errstring(module->ldb,
-                                 "Async interface called with NULL callback function or NULL context");
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-       
-       h = init_handle(req, module, req->context, req->callback);
-       if (!h) {
+       ac = talloc_zero(req, struct sort_context);
+       if (ac == NULL) {
+               ldb_oom(module->ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       ac = talloc_get_type(h->private_data, struct sort_context);
+
+       ac->module = module;
+       ac->req = req;
 
        sort_ctrls = talloc_get_type(control->data, struct ldb_server_sort_control *);
        if (!sort_ctrls) {
@@ -251,26 +270,20 @@ static int server_sort_search(struct ldb_module *module, struct ldb_request *req
                
        if (sort_ctrls[1] != NULL) {
                if (control->critical) {
-                       struct ldb_reply *ares;
-
-                       ares = talloc_zero(req, struct ldb_reply);
-                       if (!ares)
-                               return LDB_ERR_OPERATIONS_ERROR;
 
-                       /* 53 = unwilling to perform */
-                       ares->type = LDB_REPLY_DONE;
-                       if ((ret = build_response(ares, &ares->controls, 53, "sort control is not complete yet")) != LDB_SUCCESS) {
-                               return ret;
+                       /* callback immediately */
+                       ret = build_response(req, &controls,
+                                            LDB_ERR_UNWILLING_TO_PERFORM,
+                                            "sort control is not complete yet");
+                       if (ret != LDB_SUCCESS) {
+                               return ldb_module_done(req, NULL, NULL,
+                                                   LDB_ERR_OPERATIONS_ERROR);
                        }
 
-                       h->status = LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION;
-                       h->state = LDB_ASYNC_DONE;
-                       ret = ac->up_callback(module->ldb, ac->up_context, ares);
-
-                       return ret;
+                       return ldb_module_done(req, controls, NULL, ret);
                } else {
                        /* just pass the call down and don't do any sorting */
-                       ldb_next_request(module, req);
+                       return ldb_next_request(module, req);
                }
        }
 
@@ -278,181 +291,45 @@ static int server_sort_search(struct ldb_module *module, struct ldb_request *req
        ac->orderingRule = sort_ctrls[0]->orderingRule;
        ac->reverse = sort_ctrls[0]->reverse;
 
-       ac->req = talloc(req, struct ldb_request);
-       if (!ac->req)
+       ret = ldb_build_search_req_ex(&down_req, module->ldb, ac,
+                                       req->op.search.base,
+                                       req->op.search.scope,
+                                       req->op.search.tree,
+                                       req->op.search.attrs,
+                                       req->controls,
+                                       ac,
+                                       server_sort_search_callback,
+                                       req);
+       if (ret != LDB_SUCCESS) {
                return LDB_ERR_OPERATIONS_ERROR;
-
-       ac->req->operation = req->operation;
-       ac->req->op.search.base = req->op.search.base;
-       ac->req->op.search.scope = req->op.search.scope;
-       ac->req->op.search.tree = req->op.search.tree;
-       ac->req->op.search.attrs = req->op.search.attrs;
-       ac->req->controls = req->controls;
+       }
 
        /* save it locally and remove it from the list */
        /* we do not need to replace them later as we
         * are keeping the original req intact */
-       if (!save_controls(control, ac->req, &saved_controls)) {
+       if (!save_controls(control, down_req, &saved_controls)) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       ac->req->context = ac;
-       ac->req->callback = server_sort_search_callback;
-       ldb_set_timeout_from_prev_req(module->ldb, req, ac->req);
-
-       req->handle = h;
-
-       return ldb_next_request(module, ac->req);
-}
-
-static int server_sort_results(struct ldb_handle *handle)
-{
-       struct sort_context *ac;
-       struct ldb_reply *ares;
-       int i, ret;
-
-       ac = talloc_get_type(handle->private_data, struct sort_context);
-
-       ac->a = ldb_schema_attribute_by_name(ac->module->ldb, ac->attributeName);
-       ac->sort_result = 0;
-
-       ldb_qsort(ac->msgs, ac->num_msgs,
-                 sizeof(struct ldb_message *),
-                 ac, (ldb_qsort_cmp_fn_t)sort_compare);
-
-       for (i = 0; i < ac->num_msgs; i++) {
-               ares = talloc_zero(ac, struct ldb_reply);
-               if (!ares) {
-                       handle->status = LDB_ERR_OPERATIONS_ERROR;
-                       return handle->status;
-               }
-
-               ares->type = LDB_REPLY_ENTRY;
-               ares->message = talloc_move(ares, &ac->msgs[i]);
-               
-               handle->status = ac->up_callback(ac->module->ldb, ac->up_context, ares);
-               if (handle->status != LDB_SUCCESS) {
-                       return handle->status;
-               }
-       }
-
-       for (i = 0; i < ac->num_refs; i++) {
-               ares = talloc_zero(ac, struct ldb_reply);
-               if (!ares) {
-                       handle->status = LDB_ERR_OPERATIONS_ERROR;
-                       return handle->status;
-               }
-
-               ares->type = LDB_REPLY_REFERRAL;
-               ares->referral = talloc_move(ares, &ac->referrals[i]);
-               
-               handle->status = ac->up_callback(ac->module->ldb, ac->up_context, ares);
-               if (handle->status != LDB_SUCCESS) {
-                       return handle->status;
-               }
-       }
-
-       ares = talloc_zero(ac, struct ldb_reply);
-       if (!ares) {
-               handle->status = LDB_ERR_OPERATIONS_ERROR;
-               return handle->status;
-       }
-
-       ares->type = LDB_REPLY_DONE;
-       ares->controls = talloc_move(ares, &ac->controls);
-               
-       handle->status = ac->up_callback(ac->module->ldb, ac->up_context, ares);
-       if (handle->status != LDB_SUCCESS) {
-               return handle->status;
-       }
-
-       if ((ret = build_response(ac, &ac->controls, ac->sort_result, "sort control is not complete yet")) != LDB_SUCCESS) {
-               return ret;
-       }
-
-       return LDB_SUCCESS;
-}
-
-static int server_sort_wait_once(struct ldb_handle *handle)
-{
-       struct sort_context *ac;
-       int ret;
-    
-       if (!handle || !handle->private_data) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       ac = talloc_get_type(handle->private_data, struct sort_context);
-
-       ret = ldb_wait(ac->req->handle, LDB_WAIT_NONE);
-
-       if (ret != LDB_SUCCESS) {
-               handle->status = ret;
-               return ret;
-       }
-               
-       handle->state = ac->req->handle->state;
-       handle->status = ac->req->handle->status;
-
-       if (handle->status != LDB_SUCCESS) {
-               return handle->status;
-       }
-
-       if (handle->state == LDB_ASYNC_DONE) {
-               ret = server_sort_results(handle);
-       }
-
-       return ret;
-}
-
-static int server_sort_wait(struct ldb_handle *handle, enum ldb_wait_type type)
-{
-       int ret;
-       if (!handle || !handle->private_data) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       if (type == LDB_WAIT_ALL) {
-               while (handle->state != LDB_ASYNC_DONE) {
-                       ret = server_sort_wait_once(handle);
-                       if (ret != LDB_SUCCESS) {
-                               return ret;
-                       }
-               }
-
-               return handle->status;
-       }
-
-       return server_sort_wait_once(handle);
+       return ldb_next_request(module, down_req);
 }
 
 static int server_sort_init(struct ldb_module *module)
 {
-       struct ldb_request *req;
        int ret;
 
-       req = talloc(module, struct ldb_request);
-       if (req == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       req->operation = LDB_REQ_REGISTER_CONTROL;
-       req->op.reg_control.oid = LDB_CONTROL_SERVER_SORT_OID;
-       req->controls = NULL;
-
-       ret = ldb_request(module->ldb, req);
+       ret = ldb_mod_register_control(module, LDB_CONTROL_SERVER_SORT_OID);
        if (ret != LDB_SUCCESS) {
-               ldb_debug(module->ldb, LDB_DEBUG_WARNING, "server_sort: Unable to register control with rootdse!\n");
+               ldb_debug(module->ldb, LDB_DEBUG_WARNING,
+                       "server_sort:"
+                       "Unable to register control with rootdse!\n");
        }
 
-       talloc_free(req);
        return ldb_next_init(module);
 }
 
 const struct ldb_module_ops ldb_server_sort_module_ops = {
        .name              = "server_sort",
        .search            = server_sort_search,
-       .wait              = server_sort_wait,
        .init_context      = server_sort_init
 };
index 6c910b63f1b450e1de9c63ae7561d9120241ec55..e2cc65852121561d87bc2fcbb6e03a070ab18077 100755 (executable)
@@ -8,6 +8,7 @@ import sys
 import time
 
 sys.path.append("bin/python")
+sys.path.append("../lib/subunit/python")
 
 import samba.getopt as options
 
index b3d1f934a601553dce3f5d94ac74c1dc07024294..ceabd5cd78d2eb5714f1dfb62f66dc7985ab18c2 100644 (file)
@@ -56,6 +56,7 @@ static int do_compare_msg(struct ldb_message **el1,
 }
 
 struct search_context {
+       struct ldb_context *ldb;
        struct ldb_control **req_ctrls;
 
        int sort;
@@ -101,7 +102,7 @@ static int store_referral(char *referral, struct search_context *sctx) {
        return 0;
 }
 
-static int display_message(struct ldb_context *ldb, struct ldb_message *msg, struct search_context *sctx) {
+static int display_message(struct ldb_message *msg, struct search_context *sctx) {
        struct ldb_ldif ldif;
 
        sctx->entries++;
@@ -119,7 +120,7 @@ static int display_message(struct ldb_context *ldb, struct ldb_message *msg, str
                ldb_msg_sort_elements(ldif.msg);
                }
 
-       ldb_ldif_write_file(ldb, stdout, &ldif);
+       ldb_ldif_write_file(sctx->ldb, stdout, &ldif);
 
        return 0;
 }
@@ -133,18 +134,26 @@ static int display_referral(char *referral, struct search_context *sctx)
        return 0;
 }
 
-static int search_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares)
+static int search_callback(struct ldb_request *req, struct ldb_reply *ares)
 {
-       struct search_context *sctx = talloc_get_type(context, struct search_context);
+       struct search_context *sctx;
        int ret;
+
+       sctx = talloc_get_type(req->context, struct search_context);
+
+       if (!ares) {
+               return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_request_done(req, ares->error);
+       }
        
        switch (ares->type) {
-
        case LDB_REPLY_ENTRY:
                if (sctx->sort) {
                        ret = store_message(ares->message, sctx);
                } else {
-                       ret = display_message(ldb, ares->message, sctx);
+                       ret = display_message(ares->message, sctx);
                }
                break;
 
@@ -154,6 +163,9 @@ static int search_callback(struct ldb_context *ldb, void *context, struct ldb_re
                } else {
                        ret = display_referral(ares->referral, sctx);
                }
+               if (ret) {
+                       return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
+               }
                break;
 
        case LDB_REPLY_DONE:
@@ -161,22 +173,13 @@ static int search_callback(struct ldb_context *ldb, void *context, struct ldb_re
                        if (handle_controls_reply(ares->controls, sctx->req_ctrls) == 1)
                                sctx->pending = 1;
                }
-               ret = 0;
-               break;
-               
-       default:
-               fprintf(stderr, "unknown Reply Type\n");
-               return LDB_ERR_OTHER;
-       }
-
-       if (talloc_free(ares) == -1) {
-               fprintf(stderr, "talloc_free failed\n");
-               sctx->pending = 0;
-               return LDB_ERR_OPERATIONS_ERROR;
+               talloc_free(ares);
+               return ldb_request_done(req, LDB_SUCCESS);
        }
 
+       talloc_free(ares);
        if (ret) {
-               return LDB_ERR_OPERATIONS_ERROR;
+               return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
        }
 
        return LDB_SUCCESS;
@@ -192,12 +195,12 @@ static int do_search(struct ldb_context *ldb,
        struct search_context *sctx;
        int ret;
 
-       req = talloc(ldb, struct ldb_request);
-       if (!req) return -1;
+       req = NULL;
        
-       sctx = talloc(req, struct search_context);
+       sctx = talloc(ldb, struct search_context);
        if (!sctx) return -1;
 
+       sctx->ldb = ldb;
        sctx->sort = options->sorted;
        sctx->num_stored = 0;
        sctx->refs_stored = 0;
@@ -214,18 +217,22 @@ static int do_search(struct ldb_context *ldb,
                basedn = ldb_get_default_basedn(ldb);
        }
 
-       req->operation = LDB_SEARCH;
-       req->op.search.base = basedn;
-       req->op.search.scope = options->scope;
-       req->op.search.tree = ldb_parse_tree(req, expression);
-       if (req->op.search.tree == NULL) return -1;
-       req->op.search.attrs = attrs;
-       req->controls = sctx->req_ctrls;
-       req->context = sctx;
-       req->callback = &search_callback;
-       ldb_set_timeout(ldb, req, 0); /* TODO: make this settable by command line */
-
 again:
+       /* free any previous requests */
+       if (req) talloc_free(req);
+
+       ret = ldb_build_search_req(&req, ldb, ldb,
+                                  basedn, options->scope,
+                                  expression, attrs,
+                                  sctx->req_ctrls,
+                                  sctx, search_callback,
+                                  NULL);
+       if (ret != LDB_SUCCESS) {
+               talloc_free(sctx);
+               printf("allocating request failed: %s\n", ldb_errstring(ldb));
+               return -1;
+       }
+
        sctx->pending = 0;
 
        ret = ldb_request(ldb, req);
@@ -251,7 +258,7 @@ again:
                                  ldb, (ldb_qsort_cmp_fn_t)do_compare_msg);
                }
                for (i = 0; i < sctx->num_stored; i++) {
-                       display_message(ldb, sctx->store[i], sctx);
+                       display_message(sctx->store[i], sctx);
                }
 
                for (i = 0; i < sctx->refs_stored; i++) {
@@ -262,6 +269,7 @@ again:
        printf("# returned %d records\n# %d entries\n# %d referrals\n",
                sctx->entries + sctx->refs, sctx->entries, sctx->refs);
 
+       talloc_free(sctx);
        talloc_free(req);
 
        return 0;
index 6c683a1e33068eb49f8d210f7c403966a3df75b7..617371333f0f9fba1346f682932f7f362ea55963 100644 (file)
@@ -71,6 +71,7 @@ static void ldb_wrap_debug(void *context, enum ldb_debug_level level,
 static int ldb_wrap_destructor(struct ldb_context *ldb)
 {
        size_t *startup_blocks = (size_t *)ldb_get_opaque(ldb, "startup_blocks");
+
        if (startup_blocks &&
            talloc_total_blocks(ldb) > *startup_blocks + 400) {
                DEBUG(0,("WARNING: probable memory leak in ldb %s - %lu blocks (startup %lu) %lu bytes\n",
@@ -124,15 +125,6 @@ struct ldb_context *ldb_wrap_connect(TALLOC_CTX *mem_ctx,
                                            "%s/ldb",
                                            lp_modulesdir(lp_ctx)));
 
-#if 0
-       if (ev) {
-               ldb_event_sys_op_init(ldb, ev);
-       } else {
-               talloc_free(ldb);
-               return NULL;
-       }
-#endif
-
        if (ldb_set_opaque(ldb, "sessionInfo", session_info)) {
                talloc_free(ldb);
                return NULL;
@@ -198,6 +190,3 @@ struct ldb_context *ldb_wrap_connect(TALLOC_CTX *mem_ctx,
 
        return ldb;
 }
-
-
-
index d49d46250d3d7b5d70da6afe9069be84cdc1dc59..a6f947ee78966ad0f57b62e61f2ab751ca1f2b99 100644 (file)
@@ -69,7 +69,7 @@ WERROR reg_generate_diff_key(struct registry_key *oldkey,
                old_num_values = 0;
        }
 
-       /* Subkeys that were deleted */
+       /* Subkeys that were changed or deleted */
        for (i = 0; i < old_num_subkeys; i++) {
                error1 = reg_key_get_subkey_by_index(mem_ctx, oldkey, i,
                                                     &keyname1, NULL, NULL);
@@ -81,24 +81,23 @@ WERROR reg_generate_diff_key(struct registry_key *oldkey,
 
                if (newkey != NULL) {
                        error2 = reg_open_key(mem_ctx, newkey, keyname1, &t2);
-
-                       if (W_ERROR_IS_OK(error2))
-                               continue;
                } else {
                        error2 = WERR_BADFILE;
                        t2 = NULL;
                }
 
-               if (!W_ERROR_EQUAL(error2, WERR_BADFILE)) {
+               if (!W_ERROR_IS_OK(error2) && !W_ERROR_EQUAL(error2, WERR_BADFILE)) {
                        DEBUG(0, ("Error occured while getting subkey by name: %s\n",
                                win_errstr(error2)));
                        talloc_free(mem_ctx);
                        return error2;
                }
 
-               /* newkey didn't have such a subkey, add del diff */
+               /* if "error2" is going to be "WERR_BADFILE", then newkey */
+               /* didn't have such a subkey and therefore add a del diff */
                tmppath = talloc_asprintf(mem_ctx, "%s\\%s", path, keyname1);
-               callbacks->del_key(callback_data, tmppath);
+               if (!W_ERROR_IS_OK(error2))
+                       callbacks->del_key(callback_data, tmppath);
 
                /* perform here also the recursive invocation */
                error1 = reg_open_key(mem_ctx, oldkey, keyname1, &t1);
@@ -385,14 +384,13 @@ static WERROR reg_diff_apply_add_key(void *_ctx, const char *key_name)
 static WERROR reg_diff_apply_del_key(void *_ctx, const char *key_name)
 {
        struct registry_context *ctx = (struct registry_context *)_ctx;
-       WERROR error;
 
-       error = reg_key_del_abs(ctx, key_name);
+       /* We can't proof here for success, because a common superkey could */
+       /* have been deleted before the subkey's (diff order). This removed */
+       /* therefore all childs recursively and the "WERR_BADFILE" result is */
+       /* expected. */
 
-       if(!W_ERROR_IS_OK(error)) {
-               DEBUG(0, ("Unable to delete key '%s'\n", key_name));
-               return error;
-       }
+       reg_key_del_abs(ctx, key_name);
 
        return WERR_OK;
 }
@@ -454,8 +452,7 @@ static WERROR reg_diff_apply_del_all_values(void *_ctx, const char *key_name)
        struct registry_context *ctx = (struct registry_context *)_ctx;
        struct registry_key *key;
        WERROR error;
-       int i;
-       uint32_t num_values;
+       const char* value_name;
 
        error = reg_open_key_abs(ctx, ctx, key_name, &key);
 
@@ -465,14 +462,15 @@ static WERROR reg_diff_apply_del_all_values(void *_ctx, const char *key_name)
        }
 
        W_ERROR_NOT_OK_RETURN(reg_key_get_info(ctx, key, NULL,
-                              NULL, &num_values, NULL, NULL, NULL, NULL));
+                              NULL, NULL, NULL, NULL, NULL, NULL));
 
-       for (i = 0; i < num_values; i++) {
-               const char *name;
-               W_ERROR_NOT_OK_RETURN(reg_key_get_value_by_index(ctx, key, i,
-                                                                &name,
-                                                                NULL, NULL));
-               W_ERROR_NOT_OK_RETURN(reg_del_value(key, name));
+       while (W_ERROR_IS_OK(reg_key_get_value_by_index(
+                       ctx, key, 0, &value_name, NULL, NULL))) {
+               error = reg_del_value(key, value_name);
+               if (!W_ERROR_IS_OK(error)) {
+                       DEBUG(0, ("Error deleting value '%s'\n", value_name));
+                       return error;
+               }
        }
 
        return WERR_OK;
index 6eae26bc469fce13a98b1252c47af1f3b5126354..2b7eb838bafce437f55f33396dd7499ae48ba74d 100644 (file)
@@ -53,7 +53,7 @@ static bool test_reg_val_data_string_dword(struct torture_context *ctx)
 static bool test_reg_val_data_string_sz(struct torture_context *ctx)
 {
        DATA_BLOB db;
-       db.length = convert_string_talloc(ctx, lp_iconv_convenience(ctx->lp_ctx), CH_UNIX, CH_UTF16,
+       db.length = convert_string_talloc(ctx, lp_iconv_convenience(ctx->lp_ctx), CH_UTF8, CH_UTF16,
                                          "bla", 3, (void **)&db.data);
        torture_assert_str_equal(ctx, "bla",
                                 reg_val_data_string(ctx, lp_iconv_convenience(ctx->lp_ctx), REG_SZ, db),
@@ -88,7 +88,7 @@ static bool test_reg_val_data_string_empty(struct torture_context *ctx)
 static bool test_reg_val_description(struct torture_context *ctx)
 {
        DATA_BLOB data;
-       data.length = convert_string_talloc(ctx, lp_iconv_convenience(ctx->lp_ctx), CH_UNIX, CH_UTF16,
+       data.length = convert_string_talloc(ctx, lp_iconv_convenience(ctx->lp_ctx), CH_UTF8, CH_UTF16,
                                            "stationary traveller",
                                            strlen("stationary traveller"),
                                            (void **)&data.data);
@@ -102,7 +102,7 @@ static bool test_reg_val_description(struct torture_context *ctx)
 static bool test_reg_val_description_nullname(struct torture_context *ctx)
 {
        DATA_BLOB data;
-       data.length = convert_string_talloc(ctx, lp_iconv_convenience(ctx->lp_ctx), CH_UNIX, CH_UTF16,
+       data.length = convert_string_talloc(ctx, lp_iconv_convenience(ctx->lp_ctx), CH_UTF8, CH_UTF16,
                                            "west berlin",
                                            strlen("west berlin"),
                                            (void **)&data.data);
index 1e2cc2976a330a6f371c748e8913e7d7408a7668..193922973f1a8f692a7c6cff3ae06e881589f3a5 100644 (file)
@@ -12,7 +12,7 @@
     
    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
+   the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.
    
    This program is distributed in the hope that it will be useful,
@@ -105,12 +105,13 @@ static int sub_alloc(struct idr_context *idp, void *ptr, int *starting_id)
        int n, m, sh;
        struct idr_layer *p, *new;
        struct idr_layer *pa[MAX_LEVEL];
-       int l, id;
+       int l, id, oid;
        uint32_t bm;
 
        memset(pa, 0, sizeof(pa));
 
        id = *starting_id;
+restart:
        p = idp->top;
        l = idp->layers;
        pa[l--] = NULL;
@@ -124,12 +125,23 @@ static int sub_alloc(struct idr_context *idp, void *ptr, int *starting_id)
                if (m == IDR_SIZE) {
                        /* no space available go back to previous layer. */
                        l++;
+                       oid = id;
                        id = (id | ((1 << (IDR_BITS*l))-1)) + 1;
+
+                       /* if already at the top layer, we need to grow */
                        if (!(p = pa[l])) {
                                *starting_id = id;
                                return -2;
                        }
+
+                       /* If we need to go up one layer, continue the
+                        * loop; otherwise, restart from the top.
+                        */
+                       sh = IDR_BITS * (l + 1);
+                       if (oid >> sh == id >> sh)
                        continue;
+                       else
+                               goto restart;
                }
                if (m != n) {
                        sh = IDR_BITS*l;
index 32543a8ca7fcc6bd409cf04164079359b923181e..46c9b70cdbccf2a00b426b3bd38d81f2207eb154 100644 (file)
@@ -27,7 +27,7 @@
 
 /** FIXME: Use credentials struct rather than user/password here */
 WERROR WBEM_ConnectServer(struct com_context *ctx, const char *server, const char *nspace, 
-                         const char *user, const char *password, 
+                         struct cli_credentials *credentials,
                          const char *locale, uint32_t flags, const char *authority, 
                          struct IWbemContext* wbem_ctx, struct IWbemServices** services);
 const char *wmi_errstr(WERROR werror);
index 49c1e033125e27dd8cbecf6714c2c7f0979b2e7d..3ac6c89292b9a8ce000580d440b04696be27401a 100644 (file)
@@ -51,7 +51,7 @@ void wmi_init(struct com_context **ctx, struct cli_credentials *credentials)
 
 /** FIXME: Use credentials struct rather than user/password here */
 WERROR WBEM_ConnectServer(struct com_context *ctx, const char *server, const uint16_t *nspace, 
-                         const char *user, const char *password, 
+                         struct cli_credentials *credentials,
                          const char *locale, uint32_t flags, const char *authority, 
                          struct IWbemContext* wbem_ctx, struct IWbemServices** services)
 {
@@ -61,18 +61,6 @@ WERROR WBEM_ConnectServer(struct com_context *ctx, const char *server, const uin
         struct IUnknown **mqi;
         struct IWbemLevel1Login *pL;
 
-        if (user) {
-                char *cred;
-                struct cli_credentials *cc;
-
-                cred = talloc_asprintf(NULL, "%s%%%s", user, password);
-                cc = cli_credentials_init(cred);
-                cli_credentials_set_conf(cc, global_loadparm);
-                cli_credentials_parse_string(cc, cred, CRED_SPECIFIED);
-                dcom_add_server_credentials(ctx, server, cc);
-                talloc_free(cred);
-        }
-
         GUID_from_string(CLSID_WBEMLEVEL1LOGIN, &clsid);
         GUID_from_string(COM_IWBEMLEVEL1LOGIN_UUID, &iid);
         result = dcom_create_object(ctx, &clsid, server, 1, &iid, &mqi, &coresult);
index c20a7fd9353f9572f804c394463bbe939aaebbb9..e42b04cdc57426027a8d45e32d5fcac796f32dd1 100644 (file)
@@ -69,12 +69,14 @@ NTSTATUS smbcli_negprot(struct smbcli_state *cli, bool unicode, int maxprotocol)
 /* wrapper around smb_raw_sesssetup() */
 NTSTATUS smbcli_session_setup(struct smbcli_state *cli, 
                              struct cli_credentials *credentials,
-                             const char *workgroup)
+                             const char *workgroup,
+                             struct smbcli_session_options options)
 {
        struct smb_composite_sesssetup setup;
        NTSTATUS status;
 
-       cli->session = smbcli_session_init(cli->transport, cli, true);
+       cli->session = smbcli_session_init(cli->transport, cli, true,
+                                          options);
        if (!cli->session) return NT_STATUS_UNSUCCESSFUL;
 
        setup.in.sesskey = cli->transport->negotiate.sesskey;
@@ -144,7 +146,8 @@ NTSTATUS smbcli_full_connection(TALLOC_CTX *parent_ctx,
                                struct cli_credentials *credentials,
                                struct resolve_context *resolve_ctx,
                                struct event_context *ev,
-                               struct smbcli_options *options)
+                               struct smbcli_options *options,
+                               struct smbcli_session_options *session_options)
 {
        struct smbcli_tree *tree;
        NTSTATUS status;
@@ -155,7 +158,8 @@ NTSTATUS smbcli_full_connection(TALLOC_CTX *parent_ctx,
                                             &tree, host, ports, 
                                             sharename, devtype,
                                             credentials, resolve_ctx, ev,
-                                            options);
+                                            options,
+                                            session_options);
        if (!NT_STATUS_IS_OK(status)) {
                goto done;
        }
index d59a03f194c8e05d2fed5c70005e7e7dd2dac988..28563d918e2021eac4310df5b1bba96cd6f64122 100644 (file)
@@ -91,6 +91,7 @@ int smbcli_deltree(struct smbcli_tree *tree, const char *dname)
        dstate.failed = false;
 
        /* it might be a file */
+       status = smbcli_unlink(tree, dname);
        if (NT_STATUS_IS_OK(smbcli_unlink(tree, dname))) {
                return 1;
        }
index 2f81d7cff0a1a789a71bd34c4cf65ffd588c1c8c..8d9a1f5fa8bf4063da21d487dcaa0921dd9ac8ee 100644 (file)
@@ -40,46 +40,52 @@ $(eval $(call proto_header_template,$(libclisrcdir)/smb_composite/proto.h,$(LIBC
 
 [SUBSYSTEM::NDR_NBT_BUF]
 
-NDR_NBT_BUF_OBJ_FILES = $(libclinbtsrcdir)/nbt/nbtname.o
+NDR_NBT_BUF_OBJ_FILES = $(libclinbtsrcdir)/nbtname.o
 
-$(eval $(call proto_header_template,$(libclinbtsrcdir)/nbt/nbtname.h,$(NDR_NBT_BUF_OBJ_FILES:.o=.c)))
+$(eval $(call proto_header_template,$(libclinbtsrcdir)/nbtname.h,$(NDR_NBT_BUF_OBJ_FILES:.o=.c)))
 
 [SUBSYSTEM::LIBCLI_NBT]
 PUBLIC_DEPENDENCIES = LIBNDR NDR_NBT LIBCLI_COMPOSITE LIBEVENTS \
        NDR_SECURITY samba-socket LIBSAMBA-UTIL
 
-LIBCLI_NBT_OBJ_FILES = $(addprefix $(libclinbtsrcdir)/nbt/, \
+LIBCLI_NBT_OBJ_FILES = $(addprefix $(libclinbtsrcdir)/, \
        nbtsocket.o \
        namequery.o \
        nameregister.o \
        namerefresh.o \
        namerelease.o)
 
+[BINARY::nmblookup]
+INSTALLDIR = BINDIR
+PRIVATE_DEPENDENCIES = \
+               LIBSAMBA-HOSTCONFIG \
+               LIBSAMBA-UTIL \
+               LIBCLI_NBT \
+               LIBPOPT \
+               POPT_SAMBA \
+               LIBNETIF \
+               LIBCLI_RESOLVE
+
+nmblookup_OBJ_FILES = $(libclinbtsrcdir)/tools/nmblookup.o
+MANPAGES += $(libclinbtsrcdir)/man/nmblookup.1
+
 [SUBSYSTEM::LIBCLI_NDR_NETLOGON]
 PUBLIC_DEPENDENCIES = LIBNDR  \
        NDR_SECURITY    
 
-LIBCLI_NDR_NETLOGON_OBJ_FILES = $(addprefix $(libclinbtsrcdir)/, ndr_netlogon.o)
+LIBCLI_NDR_NETLOGON_OBJ_FILES = $(addprefix $(libclinbtsrcdir)/../, ndr_netlogon.o)
 
 [SUBSYSTEM::LIBCLI_NETLOGON]
 PUBLIC_DEPENDENCIES = LIBSAMBA-UTIL LIBCLI_NDR_NETLOGON
 
 LIBCLI_NETLOGON_OBJ_FILES = $(addprefix $(libclinbtsrcdir)/, \
-       netlogon.o)
-
-[SUBSYSTEM::LIBCLI_DRSBLOBS]
-PUBLIC_DEPENDENCIES = LIBNDR 
-
-LIBCLI_DRSBLOBS_OBJ_FILES = $(addprefix $(libclisrcdir)/, \
-       drsblobs.o)
-
-$(eval $(call proto_header_template,$(libclisrcdir)/drsblobs_proto.h,$(LIBCLI_DRSBLOBS_OBJ_FILES:.o=.c)))
+       ../netlogon.o)
 
 [PYTHON::python_netbios]
 LIBRARY_REALNAME = samba/netbios.$(SHLIBEXT)
 PUBLIC_DEPENDENCIES = LIBCLI_NBT DYNCONFIG LIBSAMBA-HOSTCONFIG
 
-python_netbios_OBJ_FILES = $(libclinbtsrcdir)/nbt/pynbt.o
+python_netbios_OBJ_FILES = $(libclinbtsrcdir)/pynbt.o
 
 $(python_libcli_nbt_OBJ_FILES): CFLAGS+=$(CFLAG_NO_UNUSED_MACROS) $(CFLAG_NO_CAST_QUAL)
 
diff --git a/source4/libcli/drsblobs.h b/source4/libcli/drsblobs.h
deleted file mode 100644 (file)
index 8fee411..0000000
+++ /dev/null
@@ -1,28 +0,0 @@
-/* 
-   Unix SMB/CIFS implementation.
-
-   Manually parsed structures found in the DRS protocol
-
-   Copyright (C) Andrew Bartlett <abartlet@samba.org> 2008
-   
-   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/>.
-*/
-
-#ifndef __LIBCLI_DRSBLOBS_H__
-#define __LIBCLI_DRSBLOBS_H__
-
-#include "librpc/gen_ndr/ndr_drsblobs.h"
-
-#include "libcli/drsblobs_proto.h"
-#endif /* __CLDAP_SERVER_PROTO_H__ */
index d7960f901ab707eddfa550eadac7f6151a546938..fc5863b671f32ee3d8ac4d757d35cab185542f64 100644 (file)
@@ -435,7 +435,7 @@ static void ldap_connect_got_sock(struct composite_context *ctx,
        packet_set_error_handler(conn->packet, ldap_error_handler);
        packet_set_event_context(conn->packet, conn->event.event_ctx);
        packet_set_fde(conn->packet, conn->event.fde);
-       packet_set_serialise(conn->packet);
+/*     packet_set_serialise(conn->packet); */
 
        composite_done(ctx);
 }
diff --git a/source4/libcli/nbt/man/nmblookup.1.xml b/source4/libcli/nbt/man/nmblookup.1.xml
new file mode 100644 (file)
index 0000000..85640da
--- /dev/null
@@ -0,0 +1,223 @@
+<?xml version="1.0" encoding="iso-8859-1"?>
+<!DOCTYPE refentry PUBLIC "-//Samba-Team//DTD DocBook V4.2-Based Variant V1.0//EN" "http://www.samba.org/samba/DTD/samba-doc">
+<refentry id="nmblookup">
+
+<refmeta>
+       <refentrytitle>nmblookup</refentrytitle>
+       <manvolnum>1</manvolnum>
+       <refmiscinfo class="source">Samba</refmiscinfo>
+       <refmiscinfo class="manual">User Commands</refmiscinfo>
+       <refmiscinfo class="version">3.2</refmiscinfo>
+</refmeta>
+
+
+<refnamediv>
+       <refname>nmblookup</refname>
+       <refpurpose>NetBIOS over TCP/IP client used to lookup NetBIOS 
+       names</refpurpose>
+</refnamediv>
+
+<refsynopsisdiv>
+       <cmdsynopsis>
+               <command>nmblookup</command>
+               <arg choice="opt">-M</arg>
+               <arg choice="opt">-R</arg>
+               <arg choice="opt">-S</arg>
+               <arg choice="opt">-r</arg>
+               <arg choice="opt">-A</arg>
+               <arg choice="opt">-h</arg>
+               <arg choice="opt">-B &lt;broadcast address&gt;</arg>
+               <arg choice="opt">-U &lt;unicast address&gt;</arg>
+               <arg choice="opt">-d &lt;debug level&gt;</arg>
+               <arg choice="opt">-s &lt;smb config file&gt;</arg>
+               <arg choice="opt">-i &lt;NetBIOS scope&gt;</arg>
+               <arg choice="opt">-T</arg>
+               <arg choice="opt">-f</arg>
+               <arg choice="req">name</arg>
+       </cmdsynopsis>
+</refsynopsisdiv>
+
+<refsect1>
+       <title>DESCRIPTION</title>
+
+       <para>This tool is part of the <citerefentry><refentrytitle>samba</refentrytitle>
+       <manvolnum>7</manvolnum></citerefentry> suite.</para>
+
+       <para><command>nmblookup</command> is used to query NetBIOS names 
+       and map them to IP addresses in a network using NetBIOS over TCP/IP 
+       queries. The options allow the name queries to be directed at a 
+       particular IP broadcast area or to a particular machine. All queries 
+       are done over UDP.</para>
+</refsect1>
+
+<refsect1>
+       <title>OPTIONS</title>
+
+       <variablelist>
+               <varlistentry>
+               <term>-M</term>
+               <listitem><para>Searches for a master browser by looking 
+               up the  NetBIOS name <replaceable>name</replaceable> with a 
+               type of <constant>0x1d</constant>. If <replaceable>
+               name</replaceable> is "-" then it does a lookup on the special name 
+               <constant>__MSBROWSE__</constant>. Please note that in order to 
+               use the name "-", you need to make sure "-" isn't parsed as an 
+               argument, e.g. use : 
+               <userinput>nmblookup -M -- -</userinput>.</para></listitem> 
+               </varlistentry>
+               
+               <varlistentry>
+               <term>-R</term>
+               <listitem><para>Set the recursion desired bit in the packet 
+               to do a recursive lookup. This is used when sending a name 
+               query to a machine running a WINS server and the user wishes 
+               to query the names in the WINS server.  If this bit is unset 
+               the normal (broadcast responding) NetBIOS processing code 
+               on a machine is used instead. See RFC1001, RFC1002 for details.
+               </para></listitem>
+               </varlistentry>
+               
+               <varlistentry>
+               <term>-S</term>
+               <listitem><para>Once the name query has returned an IP 
+               address then do a node status query as well. A node status 
+               query returns the NetBIOS names registered by a host.
+               </para></listitem>
+               </varlistentry>
+
+
+               <varlistentry>
+               <term>-r</term> 
+               <listitem><para>Try and bind to UDP port 137 to send and receive UDP
+               datagrams. The reason for this option is a bug in Windows 95 
+               where it ignores the source port of the requesting packet 
+               and only replies to UDP port 137. Unfortunately, on most UNIX 
+               systems root privilege is needed to bind to this port, and 
+               in addition, if the <citerefentry><refentrytitle>nmbd</refentrytitle>
+               <manvolnum>8</manvolnum></citerefentry> daemon is running on this machine it also binds to this port.
+               </para></listitem>
+               </varlistentry>
+
+
+               <varlistentry>
+               <term>-A</term>
+               <listitem><para>Interpret <replaceable>name</replaceable> as 
+               an IP Address and do a node status query on this address.</para>
+               </listitem>
+               </varlistentry>
+
+
+
+               &popt.common.connection;
+               &stdarg.help;
+
+               <varlistentry>
+               <term>-B &lt;broadcast address&gt;</term> 
+               <listitem><para>Send the query to the given broadcast address. Without 
+               this option the default behavior of nmblookup is to send the 
+               query to the broadcast address of the network interfaces as 
+               either auto-detected or defined in the <ulink 
+               url="smb.conf.5.html#INTERFACES"><parameter>interfaces</parameter>
+               </ulink> parameter of the <citerefentry><refentrytitle>smb.conf</refentrytitle>
+       <manvolnum>5</manvolnum></citerefentry> file.
+               </para></listitem>
+               </varlistentry>
+
+
+
+               <varlistentry>
+               <term>-U &lt;unicast address&gt;</term>
+               <listitem><para>Do a unicast query to the specified address or 
+               host <replaceable>unicast address</replaceable>. This option 
+               (along with the <parameter>-R</parameter> option) is needed to 
+               query a WINS server.</para></listitem>
+               </varlistentry>
+               
+               &stdarg.server.debug;   
+               &popt.common.samba;
+
+               <varlistentry>
+               <term>-T</term> 
+               <listitem><para>This causes any IP addresses found in the 
+               lookup to be looked up via a reverse DNS lookup into a 
+               DNS name, and printed out before each</para>
+               
+               <para><emphasis>IP address .... NetBIOS name</emphasis></para>
+               
+               <para> pair that is the normal output.</para></listitem>
+               </varlistentry>
+
+               <varlistentry>
+               <term>-f</term>
+               <listitem><para>
+               Show which flags apply to the name that has been looked up. Possible 
+               answers are zero or more of: Response, Authoritative, 
+               Truncated, Recursion_Desired, Recursion_Available, Broadcast.
+               </para></listitem>
+               </varlistentry>
+
+
+               <varlistentry>
+               <term>name</term>
+               <listitem><para>This is the NetBIOS name being queried. Depending 
+               upon the previous options this may be a NetBIOS name or IP address. 
+               If a NetBIOS name then the different name types may be specified 
+               by appending '#&lt;type&gt;' to the name. This name may also be
+               '*', which will return all registered names within a broadcast 
+               area.</para></listitem>
+               </varlistentry>
+       </variablelist>
+</refsect1>
+
+
+<refsect1>
+       <title>EXAMPLES</title>
+
+               <para><command>nmblookup</command> can be used to query 
+               a WINS server (in the same way <command>nslookup</command> is 
+               used to query DNS servers). To query a WINS server, <command>nmblookup</command> 
+               must be called like this:</para>
+
+               <para><command>nmblookup -U server -R 'name'</command></para>
+
+               <para>For example, running :</para>
+
+               <para><command>nmblookup -U samba.org -R 'IRIX#1B'</command></para>
+
+               <para>would query the WINS server samba.org for the domain 
+               master browser (1B name type) for the IRIX workgroup.</para>
+</refsect1>
+
+<refsect1>
+       <title>VERSION</title>
+
+       <para>This man page is correct for version 3 of 
+       the Samba suite.</para>
+</refsect1>
+
+<refsect1>
+       <title>SEE ALSO</title>
+       <para><citerefentry><refentrytitle>nmbd</refentrytitle>
+       <manvolnum>8</manvolnum></citerefentry>, <citerefentry><refentrytitle>samba</refentrytitle>
+       <manvolnum>7</manvolnum></citerefentry>, and <citerefentry><refentrytitle>smb.conf</refentrytitle>
+       <manvolnum>5</manvolnum></citerefentry>.</para>
+</refsect1>
+
+<refsect1>
+       <title>AUTHOR</title>
+       
+       <para>The original Samba software and related utilities 
+       were created by Andrew Tridgell. Samba is now developed
+       by the Samba Team as an Open Source project similar 
+       to the way the Linux kernel is developed.</para>
+       
+       <para>The original Samba man pages were written by Karl Auer. 
+       The man page sources were converted to YODL format (another 
+       excellent piece of Open Source software, available at <ulink url="ftp://ftp.icce.rug.nl/pub/unix/">
+       ftp://ftp.icce.rug.nl/pub/unix/</ulink>) and updated for the Samba 2.0 
+       release by Jeremy Allison.  The conversion to DocBook for 
+       Samba 2.2 was done by Gerald Carter. The conversion to DocBook
+       XML 4.2 for Samba 3.0 was done by Alexander Bokovoy.</para>
+</refsect1>
+
+</refentry>
index ad4ca7b4718acd597aa58081cb2fdbb2891b118e..38d8f700f234d04849c3c87ce0f0158beba0dd6a 100644 (file)
@@ -35,7 +35,8 @@
  Initialize the session context
 ****************************************************************************/
 struct smbcli_session *smbcli_session_init(struct smbcli_transport *transport, 
-                                          TALLOC_CTX *parent_ctx, bool primary)
+                                          TALLOC_CTX *parent_ctx, bool primary,
+                                          struct smbcli_session_options options)
 {
        struct smbcli_session *session;
        uint16_t flags2;
@@ -53,9 +54,7 @@ struct smbcli_session *smbcli_session_init(struct smbcli_transport *transport,
        }
        session->pid = (uint16_t)getpid();
        session->vuid = UID_FIELD_INVALID;
-       session->options.lanman_auth = lp_client_lanman_auth(global_loadparm);
-       session->options.ntlmv2_auth = lp_client_ntlmv2_auth(global_loadparm);
-       session->options.plaintext_auth = lp_client_plaintext_auth(global_loadparm);
+       session->options = options;
        
        capabilities = transport->negotiate.capabilities;
 
index 15cd70833c7c0b13810525ef7dfa4e632cde958a..4b5d2dc39787baa1dd3cad6869adb38189043ca4 100644 (file)
@@ -177,7 +177,8 @@ NTSTATUS smbcli_tree_full_connection(TALLOC_CTX *parent_ctx,
                                     struct cli_credentials *credentials,
                                     struct resolve_context *resolve_ctx,
                                     struct event_context *ev,
-                                    struct smbcli_options *options)
+                                    struct smbcli_options *options,
+                                    struct smbcli_session_options *session_options)
 {
        struct smb_composite_connect io;
        NTSTATUS status;
@@ -200,6 +201,7 @@ NTSTATUS smbcli_tree_full_connection(TALLOC_CTX *parent_ctx,
         * is complete -- abartlet 2008-04-28 */
        io.in.workgroup = lp_workgroup(global_loadparm);
        io.in.options = *options;
+       io.in.session_options = *session_options;
        
        status = smb_composite_connect(&io, parent_ctx, resolve_ctx, ev);
        if (NT_STATUS_IS_OK(status)) {
index 20ed4414350487a0c7a009a36de55de3a8ece8d6..c2269cbbc2f6d61b85ac62787997e6c31c8fceed 100644 (file)
@@ -904,6 +904,7 @@ enum smb_setfileinfo_level {
        RAW_SFILEINFO_UNIX_HLINK              = SMB_SFILEINFO_UNIX_HLINK,
        RAW_SFILEINFO_BASIC_INFORMATION       = SMB_SFILEINFO_BASIC_INFORMATION,
        RAW_SFILEINFO_RENAME_INFORMATION      = SMB_SFILEINFO_RENAME_INFORMATION,
+       RAW_SFILEINFO_LINK_INFORMATION        = SMB_SFILEINFO_LINK_INFORMATION,
        RAW_SFILEINFO_DISPOSITION_INFORMATION = SMB_SFILEINFO_DISPOSITION_INFORMATION,
        RAW_SFILEINFO_POSITION_INFORMATION    = SMB_SFILEINFO_POSITION_INFORMATION,
        RAW_SFILEINFO_FULL_EA_INFORMATION     = SMB_SFILEINFO_FULL_EA_INFORMATION,
@@ -984,6 +985,7 @@ union smb_setfileinfo {
                        NTTIME write_time;
                        NTTIME change_time;
                        uint32_t attrib;
+                       uint32_t reserved;
                } in;
        } basic_info;
 
@@ -1029,6 +1031,17 @@ union smb_setfileinfo {
                } in;
        } rename_information;
 
+       /* RAW_SFILEINFO_LINK_INFORMATION interface */
+       struct {
+               enum smb_setfileinfo_level level;
+               struct {
+                       union smb_handle_or_path file;
+                       uint8_t overwrite;
+                       uint64_t root_fid;
+                       const char *new_name;
+               } in;
+       } link_information;
+
        /* RAW_SFILEINFO_POSITION_INFORMATION interface */
        struct {
                enum smb_setfileinfo_level level;
index 2e2eb05397fc64668320f5ef00abdab54fd650ed..ca78a2ce43985588b3c50ac87354f630a36dac13 100644 (file)
@@ -75,7 +75,13 @@ struct composite_context *resolve_name_bcast_send(TALLOC_CTX *mem_ctx,
 NTSTATUS resolve_name_bcast_recv(struct composite_context *c, 
                                 TALLOC_CTX *mem_ctx, const char **reply_addr)
 {
-       return resolve_name_nbtlist_recv(c, mem_ctx, reply_addr);
+       NTSTATUS status = resolve_name_nbtlist_recv(c, mem_ctx, reply_addr);
+       if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT)) {
+               /* this makes much more sense for a bcast name resolution
+                  timeout */
+               status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
+       }
+       return status;
 }
 
 /*
index d89b50e430fd1fd6428df74cc90dab873185930d..dbc4a2ede749a58ac7e1686d94cbf654ea712f69 100644 (file)
@@ -165,6 +165,10 @@ struct composite_context *resolve_name_send(struct resolve_context *ctx,
        }
 
        state->method = ctx->methods;
+       if (state->method == NULL) {
+               composite_error(c, NT_STATUS_BAD_NETWORK_NAME);
+               return c;
+       }
        state->creq = setup_next_method(c);
        if (composite_nomem(state->creq, c)) return c;
        
index 6ba106bb5f3f05f7b11e0d337a58bdca32197467..420439d147a47baa573f6c3212c79a6a64ddac48 100644 (file)
@@ -105,6 +105,12 @@ typedef struct security_descriptor {
 %talloctype(dom_sid);
 
 typedef struct dom_sid {
+    %immutable;
+    uint8_t sid_rev_num;
+    int8_t num_auths;/* [range(0,15)] */
+    uint8_t id_auth[6];
+    uint32_t *sub_auths;
+    %mutable;
     %extend {
         dom_sid(TALLOC_CTX *mem_ctx, const char *text) {
             return dom_sid_parse_talloc(mem_ctx, text);
index c310dde56bb2de56b76eedf3c46f2dc299c50687..8afb3eda610b8e292c370f0a902fe5e3ab727c30 100644 (file)
@@ -147,6 +147,10 @@ security_descriptor_swigregister(security_descriptor)
 class Sid(object):
     thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
     __repr__ = _swig_repr
+    sid_rev_num = _swig_property(_security.Sid_sid_rev_num_get)
+    num_auths = _swig_property(_security.Sid_num_auths_get)
+    id_auth = _swig_property(_security.Sid_id_auth_get)
+    sub_auths = _swig_property(_security.Sid_sub_auths_get)
     def __init__(self, *args, **kwargs): 
         _security.Sid_swiginit(self,_security.new_Sid(*args, **kwargs))
     def __repr__(self):
index b7d66b5aec4da92233eb110a0a85674ff9c7de8f..f7e3c2fb21fd854cadc25ff29715c43831889769 100644 (file)
@@ -2712,6 +2712,28 @@ SWIGINTERN void delete_security_token(security_token *self){ talloc_free(self);
 SWIGINTERN security_descriptor *new_security_descriptor(TALLOC_CTX *mem_ctx){ return security_descriptor_initialise(mem_ctx); }
 SWIGINTERN void delete_security_descriptor(security_descriptor *self){ talloc_free(self); }
 
+SWIGINTERNINLINE PyObject* 
+SWIG_From_unsigned_SS_long  (unsigned long value)
+{
+  return (value > LONG_MAX) ?
+    PyLong_FromUnsignedLong(value) : PyInt_FromLong((long)(value)); 
+}
+
+
+SWIGINTERNINLINE PyObject *
+SWIG_From_unsigned_SS_char  (unsigned char value)
+{    
+  return SWIG_From_unsigned_SS_long  (value);
+}
+
+
+SWIGINTERNINLINE PyObject *
+SWIG_From_signed_SS_char  (signed char value)
+{    
+  return SWIG_From_long  (value);
+}
+
+
 SWIGINTERN swig_type_info*
 SWIG_pchar_descriptor(void)
 {
@@ -3337,6 +3359,98 @@ SWIGINTERN PyObject *security_descriptor_swiginit(PyObject *SWIGUNUSEDPARM(self)
   return SWIG_Python_InitShadowInstance(args);
 }
 
+SWIGINTERN PyObject *_wrap_Sid_sid_rev_num_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  dom_sid *arg1 = (dom_sid *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[1] ;
+  uint8_t result;
+  
+  if (!args) SWIG_fail;
+  swig_obj[0] = args;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_dom_sid, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Sid_sid_rev_num_get" "', argument " "1"" of type '" "dom_sid *""'"); 
+  }
+  arg1 = (dom_sid *)(argp1);
+  result = (uint8_t) ((arg1)->sid_rev_num);
+  resultobj = SWIG_From_unsigned_SS_char((unsigned char)(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_Sid_num_auths_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  dom_sid *arg1 = (dom_sid *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[1] ;
+  int8_t result;
+  
+  if (!args) SWIG_fail;
+  swig_obj[0] = args;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_dom_sid, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Sid_num_auths_get" "', argument " "1"" of type '" "dom_sid *""'"); 
+  }
+  arg1 = (dom_sid *)(argp1);
+  result = (int8_t) ((arg1)->num_auths);
+  resultobj = SWIG_From_signed_SS_char((signed char)(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_Sid_id_auth_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  dom_sid *arg1 = (dom_sid *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[1] ;
+  uint8_t *result = 0 ;
+  
+  if (!args) SWIG_fail;
+  swig_obj[0] = args;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_dom_sid, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Sid_id_auth_get" "', argument " "1"" of type '" "dom_sid *""'"); 
+  }
+  arg1 = (dom_sid *)(argp1);
+  result = (uint8_t *)(uint8_t *) ((arg1)->id_auth);
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_unsigned_char, 0 |  0 );
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_Sid_sub_auths_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  dom_sid *arg1 = (dom_sid *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[1] ;
+  uint32_t *result = 0 ;
+  
+  if (!args) SWIG_fail;
+  swig_obj[0] = args;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_dom_sid, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Sid_sub_auths_get" "', argument " "1"" of type '" "dom_sid *""'"); 
+  }
+  arg1 = (dom_sid *)(argp1);
+  result = (uint32_t *) ((arg1)->sub_auths);
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_unsigned_int, 0 |  0 );
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
 SWIGINTERN PyObject *_wrap_new_Sid(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {
   PyObject *resultobj = 0;
   TALLOC_CTX *arg1 = (TALLOC_CTX *) 0 ;
@@ -3561,6 +3675,10 @@ static PyMethodDef SwigMethods[] = {
         { (char *)"delete_security_descriptor", (PyCFunction)_wrap_delete_security_descriptor, METH_O, NULL},
         { (char *)"security_descriptor_swigregister", security_descriptor_swigregister, METH_VARARGS, NULL},
         { (char *)"security_descriptor_swiginit", security_descriptor_swiginit, METH_VARARGS, NULL},
+        { (char *)"Sid_sid_rev_num_get", (PyCFunction)_wrap_Sid_sid_rev_num_get, METH_O, NULL},
+        { (char *)"Sid_num_auths_get", (PyCFunction)_wrap_Sid_num_auths_get, METH_O, NULL},
+        { (char *)"Sid_id_auth_get", (PyCFunction)_wrap_Sid_id_auth_get, METH_O, NULL},
+        { (char *)"Sid_sub_auths_get", (PyCFunction)_wrap_Sid_sub_auths_get, METH_O, NULL},
         { (char *)"new_Sid", (PyCFunction) _wrap_new_Sid, METH_VARARGS | METH_KEYWORDS, NULL},
         { (char *)"Sid___str__", (PyCFunction)_wrap_Sid___str__, METH_O, NULL},
         { (char *)"Sid___eq__", (PyCFunction) _wrap_Sid___eq__, METH_VARARGS | METH_KEYWORDS, NULL},
index 43151943d32ff309ab7ae0ac0e5a0a8efb861d88..bbfcf010aef36763eb5633695006da191744c85b 100644 (file)
@@ -184,8 +184,8 @@ static void continue_socket(struct composite_context *creq)
        }
        state->negprot.in.capabilities  = 0;
        unix_to_nt_time(&state->negprot.in.start_time, time(NULL));
-       dialects[0] = 0;
-       dialects[1] = SMB2_DIALECT_REVISION;
+       dialects[0] = SMB2_DIALECT_REVISION;
+       dialects[1] = 0;
        state->negprot.in.dialects = dialects;
 
        req = smb2_negprot_send(transport, &state->negprot);
@@ -206,7 +206,13 @@ static void continue_resolve(struct composite_context *creq)
        struct smb2_connect_state *state = talloc_get_type(c->private_data, 
                                                           struct smb2_connect_state);
        const char *addr;
-       const char *ports[2] = { "445", NULL };
+       const char **ports;
+       const char *default_ports[] = { "445", NULL };
+
+       ports = lp_parm_string_list(state, global_loadparm, NULL, "smb2", "ports", NULL);
+       if (ports == NULL) {
+               ports = default_ports;
+       }
 
        c->status = resolve_name_recv(creq, state, &addr);
        if (!composite_is_ok(c)) return;
index 64d427f889c196de06b554b4576f0ef20d60c9b4..137e2f2f12dee0f745443781104c0dadfaec4e21 100644 (file)
@@ -279,7 +279,7 @@ NTSTATUS smb2_pull_o16s16_blob(struct smb2_request_buffer *buf, TALLOC_CTX *mem_
 {
        uint16_t ofs, size;
        if (smb2_oob(buf, ptr, 4)) {
-               return NT_STATUS_BUFFER_TOO_SMALL;
+               return NT_STATUS_INVALID_PARAMETER;
        }
        ofs  = SVAL(ptr, 0);
        size = SVAL(ptr, 2);
@@ -288,7 +288,7 @@ NTSTATUS smb2_pull_o16s16_blob(struct smb2_request_buffer *buf, TALLOC_CTX *mem_
                return NT_STATUS_OK;
        }
        if (smb2_oob(buf, buf->hdr + ofs, size)) {
-               return NT_STATUS_BUFFER_TOO_SMALL;
+               return NT_STATUS_INVALID_PARAMETER;
        }
        *blob = data_blob_talloc(mem_ctx, buf->hdr + ofs, size);
        NT_STATUS_HAVE_NO_MEMORY(blob->data);
@@ -315,12 +315,12 @@ NTSTATUS smb2_push_o16s16_blob(struct smb2_request_buffer *buf,
 
        /* we have only 16 bit for the size */
        if (blob.length > 0xFFFF) {
-               return NT_STATUS_BUFFER_TOO_SMALL;
+               return NT_STATUS_INVALID_PARAMETER;
        }
 
        /* check if there're enough room for ofs and size */
        if (smb2_oob(buf, ptr, 4)) {
-               return NT_STATUS_BUFFER_TOO_SMALL;
+               return NT_STATUS_INVALID_PARAMETER;
        }
 
        if (blob.data == NULL) {
@@ -376,7 +376,7 @@ NTSTATUS smb2_push_o16s32_blob(struct smb2_request_buffer *buf,
 
        /* check if there're enough room for ofs and size */
        if (smb2_oob(buf, ptr, 6)) {
-               return NT_STATUS_BUFFER_TOO_SMALL;
+               return NT_STATUS_INVALID_PARAMETER;
        }
 
        if (blob.data == NULL) {
@@ -432,7 +432,7 @@ NTSTATUS smb2_push_o32s32_blob(struct smb2_request_buffer *buf,
 
        /* check if there're enough room for ofs and size */
        if (smb2_oob(buf, ptr, 8)) {
-               return NT_STATUS_BUFFER_TOO_SMALL;
+               return NT_STATUS_INVALID_PARAMETER;
        }
 
        if (blob.data == NULL) {
@@ -488,7 +488,7 @@ NTSTATUS smb2_push_s32o32_blob(struct smb2_request_buffer *buf,
 
        /* check if there're enough room for ofs and size */
        if (smb2_oob(buf, ptr, 8)) {
-               return NT_STATUS_BUFFER_TOO_SMALL;
+               return NT_STATUS_INVALID_PARAMETER;
        }
 
        if (blob.data == NULL) {
@@ -533,7 +533,7 @@ NTSTATUS smb2_pull_o16s32_blob(struct smb2_request_buffer *buf, TALLOC_CTX *mem_
        uint32_t size;
 
        if (smb2_oob(buf, ptr, 6)) {
-               return NT_STATUS_BUFFER_TOO_SMALL;
+               return NT_STATUS_INVALID_PARAMETER;
        }
        ofs  = SVAL(ptr, 0);
        size = IVAL(ptr, 2);
@@ -542,7 +542,7 @@ NTSTATUS smb2_pull_o16s32_blob(struct smb2_request_buffer *buf, TALLOC_CTX *mem_
                return NT_STATUS_OK;
        }
        if (smb2_oob(buf, buf->hdr + ofs, size)) {
-               return NT_STATUS_BUFFER_TOO_SMALL;
+               return NT_STATUS_INVALID_PARAMETER;
        }
        *blob = data_blob_talloc(mem_ctx, buf->hdr + ofs, size);
        NT_STATUS_HAVE_NO_MEMORY(blob->data);
@@ -557,7 +557,7 @@ NTSTATUS smb2_pull_o32s32_blob(struct smb2_request_buffer *buf, TALLOC_CTX *mem_
 {
        uint32_t ofs, size;
        if (smb2_oob(buf, ptr, 8)) {
-               return NT_STATUS_BUFFER_TOO_SMALL;
+               return NT_STATUS_INVALID_PARAMETER;
        }
        ofs  = IVAL(ptr, 0);
        size = IVAL(ptr, 4);
@@ -566,7 +566,7 @@ NTSTATUS smb2_pull_o32s32_blob(struct smb2_request_buffer *buf, TALLOC_CTX *mem_
                return NT_STATUS_OK;
        }
        if (smb2_oob(buf, buf->hdr + ofs, size)) {
-               return NT_STATUS_BUFFER_TOO_SMALL;
+               return NT_STATUS_INVALID_PARAMETER;
        }
        *blob = data_blob_talloc(mem_ctx, buf->hdr + ofs, size);
        NT_STATUS_HAVE_NO_MEMORY(blob->data);
@@ -584,7 +584,7 @@ NTSTATUS smb2_pull_o16As32_blob(struct smb2_request_buffer *buf, TALLOC_CTX *mem
 {
        uint32_t ofs, size;
        if (smb2_oob(buf, ptr, 8)) {
-               return NT_STATUS_BUFFER_TOO_SMALL;
+               return NT_STATUS_INVALID_PARAMETER;
        }
        ofs  = SVAL(ptr, 0);
        size = IVAL(ptr, 4);
@@ -593,7 +593,7 @@ NTSTATUS smb2_pull_o16As32_blob(struct smb2_request_buffer *buf, TALLOC_CTX *mem
                return NT_STATUS_OK;
        }
        if (smb2_oob(buf, buf->hdr + ofs, size)) {
-               return NT_STATUS_BUFFER_TOO_SMALL;
+               return NT_STATUS_INVALID_PARAMETER;
        }
        *blob = data_blob_talloc(mem_ctx, buf->hdr + ofs, size);
        NT_STATUS_HAVE_NO_MEMORY(blob->data);
@@ -608,7 +608,7 @@ NTSTATUS smb2_pull_s32o32_blob(struct smb2_request_buffer *buf, TALLOC_CTX *mem_
 {
        uint32_t ofs, size;
        if (smb2_oob(buf, ptr, 8)) {
-               return NT_STATUS_BUFFER_TOO_SMALL;
+               return NT_STATUS_INVALID_PARAMETER;
        }
        size = IVAL(ptr, 0);
        ofs  = IVAL(ptr, 4);
@@ -617,7 +617,31 @@ NTSTATUS smb2_pull_s32o32_blob(struct smb2_request_buffer *buf, TALLOC_CTX *mem_
                return NT_STATUS_OK;
        }
        if (smb2_oob(buf, buf->hdr + ofs, size)) {
-               return NT_STATUS_BUFFER_TOO_SMALL;
+               return NT_STATUS_INVALID_PARAMETER;
+       }
+       *blob = data_blob_talloc(mem_ctx, buf->hdr + ofs, size);
+       NT_STATUS_HAVE_NO_MEMORY(blob->data);
+       return NT_STATUS_OK;
+}
+
+/*
+  pull a uint32_t length/ uint16_t ofs/blob triple from a data blob
+  the ptr points to the start of the offset/length pair
+*/
+NTSTATUS smb2_pull_s32o16_blob(struct smb2_request_buffer *buf, TALLOC_CTX *mem_ctx, uint8_t *ptr, DATA_BLOB *blob)
+{
+       uint32_t ofs, size;
+       if (smb2_oob(buf, ptr, 8)) {
+               return NT_STATUS_INVALID_PARAMETER;
+       }
+       size = IVAL(ptr, 0);
+       ofs  = SVAL(ptr, 4);
+       if (ofs == 0) {
+               *blob = data_blob(NULL, 0);
+               return NT_STATUS_OK;
+       }
+       if (smb2_oob(buf, buf->hdr + ofs, size)) {
+               return NT_STATUS_INVALID_PARAMETER;
        }
        *blob = data_blob_talloc(mem_ctx, buf->hdr + ofs, size);
        NT_STATUS_HAVE_NO_MEMORY(blob->data);
index f00107de603b1f803ddd3967727725a22a70d31a..9d63a4a95ff168dd1f2d1a8cde60a718117b87bd 100644 (file)
@@ -178,6 +178,7 @@ struct smb2_request {
 
 
 #define SMB2_MIN_SIZE 0x42
+#define SMB2_MIN_SIZE_NO_BODY 0x40
 
 /* offsets into header elements for a sync SMB2 request */
 #define SMB2_HDR_PROTOCOL_ID    0x00
index b149b3d6cec3a19a5a65ac228352ea95da1307d8..a360d8fbdff3c357946dd6cb240659ce3da8f4dd 100644 (file)
@@ -138,7 +138,7 @@ int smb2_deltree(struct smb2_tree *tree, const char *dname)
        }
 
        ZERO_STRUCT(create_parm);
-       create_parm.in.desired_access = SEC_FLAG_MAXIMUM_ALLOWED;
+       create_parm.in.desired_access = SEC_FILE_READ_DATA;
        create_parm.in.share_access = 
                NTCREATEX_SHARE_ACCESS_READ|
                NTCREATEX_SHARE_ACCESS_WRITE;
index e56339f96bf2d6a8b624ab437a1ee0604ab979fd..a4137290bbcb714c44689d62964cc1d478c06a9d 100644 (file)
@@ -234,7 +234,7 @@ static NTSTATUS connect_negprot(struct composite_context *c,
        NT_STATUS_NOT_OK_RETURN(status);
 
        /* next step is a session setup */
-       state->session = smbcli_session_init(state->transport, state, true);
+       state->session = smbcli_session_init(state->transport, state, true, io->in.session_options);
        NT_STATUS_HAVE_NO_MEMORY(state->session);
        
        /* setup for a tconx (or at least have the structure ready to
index 9cd02a51f457b5f45299b2147418b0e52ac428fd..ff4f0e793026e4c8e8ff1e2cd3c9d4f74ca2c77e 100644 (file)
@@ -147,6 +147,7 @@ struct composite_context *smb_composite_fetchfile_send(struct smb_composite_fetc
        state->connect->in.workgroup    = io->in.workgroup;
 
        state->connect->in.options      = io->in.options;
+       state->connect->in.session_options = io->in.session_options;
 
        state->creq = smb_composite_connect_send(state->connect, state, 
                                                 io->in.resolve_ctx, event_ctx);
index 270d71f5185be629951f6e1ca588010e6971a054..dc5327a29cac4b424c0c58c183e073e2190240de 100644 (file)
@@ -127,7 +127,8 @@ static void fsinfo_composite_handler(struct composite_context *creq)
   composite fsinfo call - connects to a tree and queries a file system information
 */
 struct composite_context *smb_composite_fsinfo_send(struct smbcli_tree *tree, 
-                                                   struct smb_composite_fsinfo *io)
+                                                   struct smb_composite_fsinfo *io,
+                                                   struct resolve_context *resolve_ctx)
 {
        struct composite_context *c;
        struct fsinfo_state *state;
@@ -154,13 +155,14 @@ struct composite_context *smb_composite_fsinfo_send(struct smbcli_tree *tree,
        state->connect->in.workgroup    = io->in.workgroup;
 
        state->connect->in.options = tree->session->transport->options;
+       state->connect->in.session_options = tree->session->options;
 
        c->state = COMPOSITE_STATE_IN_PROGRESS;
        state->stage = FSINFO_CONNECT;
        c->private_data = state;
 
        state->creq = smb_composite_connect_send(state->connect, state,
-                        lp_resolve_context(global_loadparm), c->event_ctx);
+                        resolve_ctx, c->event_ctx);
 
        if (state->creq == NULL) goto failed;
   
@@ -197,9 +199,10 @@ NTSTATUS smb_composite_fsinfo_recv(struct composite_context *c, TALLOC_CTX *mem_
 */
 NTSTATUS smb_composite_fsinfo(struct smbcli_tree *tree, 
                              TALLOC_CTX *mem_ctx,
-                             struct smb_composite_fsinfo *io)
+                             struct smb_composite_fsinfo *io,
+                             struct resolve_context *resolve_ctx)
 {
-       struct composite_context *c = smb_composite_fsinfo_send(tree, io);
+       struct composite_context *c = smb_composite_fsinfo_send(tree, io, resolve_ctx);
        return smb_composite_fsinfo_recv(c, mem_ctx);
 }
 
index 7f4b9d73e4b48da338817e9558b39018119b6a25..08ca40c833072ce4260e8b619f3f97762186a70b 100644 (file)
@@ -57,6 +57,7 @@ struct smb_composite_fetchfile {
                const char *workgroup;
                const char *filename;
                struct smbcli_options options;
+               struct smbcli_session_options session_options;
                struct resolve_context *resolve_ctx;
        } in;
        struct {
@@ -98,6 +99,7 @@ struct smb_composite_connect {
                bool fallback_to_anonymous;
                const char *workgroup;
                struct smbcli_options options;
+               struct smbcli_session_options session_options;
        } in;
        struct {
                struct smbcli_tree *tree;
index b9071d5eb1dbbae8f16c2bf2570cefb598503800..4cbebbf6d0af1a69f45170eb36c514b903485263 100644 (file)
@@ -770,7 +770,7 @@ static void becomeDC_recv_cldap(struct cldap_request *req)
        c->status = cldap_netlogon_recv(req, s, &s->cldap.io);
        if (!composite_is_ok(c)) return;
 
-       s->cldap.netlogon = s->cldap.io.out.netlogon.nt5_ex;
+       s->cldap.netlogon = s->cldap.io.out.netlogon.data.nt5_ex;
 
        s->domain.dns_name              = s->cldap.netlogon.dns_domain;
        s->domain.netbios_name          = s->cldap.netlogon.domain;
index 0c4d3e5c595342720675227f4988f63a43a297f8..4b71b0c24da47a8ec32a7ee2f55d52621bdc1176 100644 (file)
@@ -68,6 +68,11 @@ static NTSTATUS samdump_keytab_handle_user(TALLOC_CTX *mem_ctx,
        return NT_STATUS_OK;
 }
 
+struct libnet_samdump_keytab_data {
+       const char *keytab_name;
+       struct loadparm_context *lp_ctx;
+};
+
 static NTSTATUS libnet_samdump_keytab_fn(TALLOC_CTX *mem_ctx,          
                                         void *private,                         
                                         enum netr_SamDatabaseID database,
@@ -75,8 +80,7 @@ static NTSTATUS libnet_samdump_keytab_fn(TALLOC_CTX *mem_ctx,
                                         char **error_string)
 {
        NTSTATUS nt_status = NT_STATUS_OK;
-       const char *keytab_name = private;
-
+       struct libnet_samdump_keytab_data *data = private; 
        *error_string = NULL;
        switch (delta->delta_type) {
        case NETR_DELTA_USER:
@@ -85,8 +89,8 @@ static NTSTATUS libnet_samdump_keytab_fn(TALLOC_CTX *mem_ctx,
                if (database == SAM_DATABASE_DOMAIN) {
                        nt_status = samdump_keytab_handle_user(mem_ctx, 
                                                               event_context_find(mem_ctx),
-                                                              global_loadparm,
-                                                              keytab_name,
+                                                              data->lp_ctx,
+                                                              data->keytab_name,
                                                               delta);
                        break;
                }
@@ -101,14 +105,18 @@ static NTSTATUS libnet_samdump_keytab_fn(TALLOC_CTX *mem_ctx,
 NTSTATUS libnet_SamDump_keytab(struct libnet_context *ctx, TALLOC_CTX *mem_ctx, struct libnet_SamDump_keytab *r)
 {
        NTSTATUS nt_status;
+       struct libnet_samdump_keytab_data data;
        struct libnet_SamSync r2;
 
+       data.keytab_name = r->in.keytab_name;
+       data.lp_ctx = ctx->lp_ctx;
+
        r2.out.error_string            = NULL;
        r2.in.binding_string           = r->in.binding_string;
        r2.in.rid_crypt                = true;
        r2.in.init_fn                  = NULL;
        r2.in.delta_fn                 = libnet_samdump_keytab_fn;
-       r2.in.fn_ctx                   = discard_const(r->in.keytab_name);
+       r2.in.fn_ctx                   = &data;
        r2.in.machine_account          = r->in.machine_account;
        nt_status                      = libnet_SamSync_netlogon(ctx, mem_ctx, &r2);
        r->out.error_string            = r2.out.error_string;
index bb65de1f54be4837d24ae67df656f1d11a42a15e..4a32ab92ed58b4a1e6559ecfac473f254e29eac1 100644 (file)
@@ -56,9 +56,10 @@ NTSTATUS libnet_FindSite(TALLOC_CTX *ctx, struct libnet_context *lctx, struct li
        search.in.version = NETLOGON_NT_VERSION_5 | NETLOGON_NT_VERSION_5EX;
        search.in.map_response = true;
 
-       cldap = cldap_socket_init(tmp_ctx, lctx->event_ctx, lp_iconv_convenience(global_loadparm));
+       cldap = cldap_socket_init(tmp_ctx, lctx->event_ctx, lp_iconv_convenience(lctx->lp_ctx));
        status = cldap_netlogon(cldap, tmp_ctx, &search);
-       if (!NT_STATUS_IS_OK(status) || !search.out.netlogon.nt5_ex.client_site) {
+       if (!NT_STATUS_IS_OK(status)
+           || !search.out.netlogon.data.nt5_ex.client_site) {
                /*
                  If cldap_netlogon() returns in error,
                  default to using Default-First-Site-Name.
@@ -72,7 +73,7 @@ NTSTATUS libnet_FindSite(TALLOC_CTX *ctx, struct libnet_context *lctx, struct li
                }
        } else {
                site_name_str = talloc_asprintf(tmp_ctx, "%s",
-                                       search.out.netlogon.nt5_ex.client_site);
+                                       search.out.netlogon.data.nt5_ex.client_site);
                if (!site_name_str) {
                        r->out.error_string = NULL;
                        talloc_free(tmp_ctx);
index 4eeaf1b80c306b0b062e739791d3739f8c254da2..2ee3c641b2bb7afb01ede8e3b7e6e2a38edb767b 100644 (file)
@@ -289,7 +289,7 @@ static void unbecomeDC_recv_cldap(struct cldap_request *req)
        c->status = cldap_netlogon_recv(req, s, &s->cldap.io);
        if (!composite_is_ok(c)) return;
 
-       s->cldap.netlogon = s->cldap.io.out.netlogon.nt5_ex;
+       s->cldap.netlogon = s->cldap.io.out.netlogon.data.nt5_ex;
 
        s->domain.dns_name              = s->cldap.netlogon.dns_domain;
        s->domain.netbios_name          = s->cldap.netlogon.domain;
@@ -641,7 +641,7 @@ static void unbecomeDC_drsuapi_remove_ds_server_send(struct libnet_UnbecomeDC_st
        r->in.level             = 1;
        r->in.req.req1.server_dn= s->dest_dsa.server_dn_str;
        r->in.req.req1.domain_dn= s->domain.dn_str;
-       r->in.req.req1.unknown  = 0x00000001;
+       r->in.req.req1.commit   = true;
 
        req = dcerpc_drsuapi_DsRemoveDSServer_send(s->drsuapi.pipe, s, r);
        composite_continue_rpc(c, req, unbecomeDC_drsuapi_remove_ds_server_recv, s);
@@ -666,11 +666,6 @@ static void unbecomeDC_drsuapi_remove_ds_server_recv(struct rpc_request *req)
                composite_error(c, NT_STATUS_INVALID_NETWORK_RESPONSE);
                return;
        }
-               
-       if (!W_ERROR_IS_OK(r->out.res.res1.status)) {
-               composite_error(c, werror_to_ntstatus(r->out.res.res1.status));
-               return;
-       }
 
        composite_done(c);
 }
index cf41f9884a2b2ae8cf8e0334fd4bb987e3713d8a..41dd17e428522bd100dd08b8d4e121b805d8e3a1 100644 (file)
@@ -144,9 +144,9 @@ PUBLIC_DEPENDENCIES = LIBNDR NDR_COMPRESSION NDR_SECURITY NDR_SAMR ASN1_UTIL
 NDR_DRSUAPI_OBJ_FILES = $(gen_ndrsrcdir)/ndr_drsuapi.o $(ndrsrcdir)/ndr_drsuapi.o
 
 [SUBSYSTEM::NDR_DRSBLOBS]
-PUBLIC_DEPENDENCIES = LIBNDR NDR_MISC NDR_DRSUAPI LIBCLI_DRSBLOBS
+PUBLIC_DEPENDENCIES = LIBNDR NDR_MISC NDR_DRSUAPI
 
-NDR_DRSBLOBS_OBJ_FILES = $(gen_ndrsrcdir)/ndr_drsblobs.o
+NDR_DRSBLOBS_OBJ_FILES = $(gen_ndrsrcdir)/ndr_drsblobs.o $(ndrsrcdir)/ndr_drsblobs.o
 
 [SUBSYSTEM::NDR_SASL_HELPERS]
 PUBLIC_DEPENDENCIES = LIBNDR
index 1c6574b11be905bda02791ac9b804ea009fcbe23..a78329d9908bd1d24a77c279ae2136a07b3016f4 100644 (file)
@@ -261,6 +261,7 @@ interface dcerpc
        const uint8 DCERPC_PFC_FLAG_OBJECT_UUID         = 0x80; /* on valid guid is in the optional object field */
 
        /* these offsets are needed by the signing code */
+       const uint8 DCERPC_PFC_OFFSET      =  3;
        const uint8 DCERPC_DREP_OFFSET     =  4;
        const uint8 DCERPC_FRAG_LEN_OFFSET =  8;
        const uint8 DCERPC_AUTH_LEN_OFFSET = 10;
index 6b1f649ff53ad311257c95e75a5fc26e74ea9cc5..4274d2000a10f2d6ab6bc7bcfc3a728f310fb7a8 100644 (file)
@@ -409,24 +409,35 @@ interface drsblobs {
                [size_is(1)] AuthenticationInformation array[];
        } AuthenticationInformationArray;
 
+       /* This is nopull,nopush because we pass count down to the
+        * manual parser of AuthenticationInformationArray */
        typedef [public,nopull,nopush,noprint,gensize] struct {
                uint32 count;
                [relative] AuthenticationInformationArray *current;
                [relative] AuthenticationInformationArray *previous;
        } trustAuthInOutBlob;
 
-       typedef [public] struct {
-               uint8 confounder[512];
-               trustAuthInOutBlob outgoing;
-               trustAuthInOutBlob incoming;
-               [value(ndr_size_trustAuthInOutBlob(&outgoing, ndr->flags))] uint32 outgoing_size;
-               [value(ndr_size_trustAuthInOutBlob(&incoming, ndr->flags))] uint32 incoming_size;
-       } trustAuthInAndOutBlob;
-       
        void decode_trustAuthInOut(
                [in] trustAuthInOutBlob blob
                );
 
+       typedef [public,gensize] struct {
+               uint32 count;
+               [relative] AuthenticationInformation *current[count];
+       } trustCurrentPasswords;
+
+       typedef [public,nopull] struct {
+               uint8 confounder[512];
+               [subcontext(0),subcontext_size(outgoing_size)] trustCurrentPasswords outgoing;
+               [subcontext(0),subcontext_size(incoming_size)] trustCurrentPasswords incoming;
+               [value(ndr_size_trustCurrentPasswords(&outgoing, ndr->flags))] uint32 outgoing_size;
+               [value(ndr_size_trustCurrentPasswords(&incoming, ndr->flags))] uint32 incoming_size;
+       } trustDomainPasswords;
+
+       void decode_trustDomainPasswords(
+               [in] trustDomainPasswords blob
+               );
+
        typedef [public] struct {
                uint32 marker;
                DATA_BLOB data;
index 0a5a081dd7fad9b016e837b9f2247d2cca68a474..a41bc9cf199f88306f1642b51e3787ccaddf5bd9 100644 (file)
@@ -877,7 +877,7 @@ interface drsuapi
        } drsuapi_DsNameFlags;
 
        typedef [v1_enum] enum {
-               DRSUAPI_DS_NAME_FORMAT_UKNOWN                   = 0,
+               DRSUAPI_DS_NAME_FORMAT_UNKNOWN                  = 0,
                DRSUAPI_DS_NAME_FORMAT_FQDN_1779                = 1,
                DRSUAPI_DS_NAME_FORMAT_NT4_ACCOUNT              = 2,
                DRSUAPI_DS_NAME_FORMAT_DISPLAY                  = 3,
@@ -970,7 +970,7 @@ interface drsuapi
        typedef struct {
                [charset(UTF16),string] uint16 *server_dn;
                [charset(UTF16),string] uint16 *domain_dn;
-               uint32 unknown; /* 0x000000001 */
+               boolean32 commit;
        } drsuapi_DsRemoveDSServerRequest1;
 
        typedef [switch_type(int32)] union {
@@ -978,7 +978,7 @@ interface drsuapi
        } drsuapi_DsRemoveDSServerRequest;
 
        typedef struct {
-               WERROR status;
+               boolean32 last_dc_in_domain;
        } drsuapi_DsRemoveDSServerResult1;
 
        typedef [switch_type(int32)] union {
index 9a6e4a202c42d432e652547f74c4848d436e8a9d..4dce6d6d1e7d72c3fcd9fb32346f2f897d18f586 100644 (file)
@@ -140,12 +140,11 @@ import "misc.idl", "security.idl";
 
        typedef struct {
                uint32 percent_full;
-               uint32 log_size;
-               NTTIME retention_time;
+               uint32 maximum_log_size;
+               hyper  retention_time;
                uint8  shutdown_in_progress;
-               NTTIME time_to_shutdown;
+               hyper  time_to_shutdown;
                uint32 next_audit_record;
-               uint32 unknown;
        } lsa_AuditLogInfo;
 
        typedef [v1_enum] enum {
@@ -183,9 +182,13 @@ import "misc.idl", "security.idl";
                lsa_String name;
        } lsa_PDAccountInfo;
 
+       typedef [v1_enum] enum {
+               LSA_ROLE_BACKUP=2,
+               LSA_ROLE_PRIMARY=3
+       } lsa_Role;
+
        typedef struct {
-               uint16 unknown; /* an midl padding bug? */
-               uint16 role;
+               lsa_Role role;
        } lsa_ServerRole;
 
        typedef struct {
@@ -204,7 +207,7 @@ import "misc.idl", "security.idl";
 
        typedef struct {
                hyper modified_id;
-               NTTIME db_create_time;
+               NTTIME_hyper db_create_time;
        } lsa_ModificationInfo;
 
        typedef struct {
@@ -212,7 +215,6 @@ import "misc.idl", "security.idl";
        } lsa_AuditFullSetInfo;
 
        typedef struct {
-               uint16 unknown; /* an midl padding bug? */
                uint8 shutdown_on_full;
                uint8 log_is_full;
        } lsa_AuditFullQueryInfo;
@@ -243,7 +245,8 @@ import "misc.idl", "security.idl";
                LSA_POLICY_INFO_DB=9,
                LSA_POLICY_INFO_AUDIT_FULL_SET=10,
                LSA_POLICY_INFO_AUDIT_FULL_QUERY=11,
-               LSA_POLICY_INFO_DNS=12
+               LSA_POLICY_INFO_DNS=12,
+               LSA_POLICY_INFO_DNS_INT=13
        } lsa_PolicyInfo;
 
        typedef [switch_type(uint16)] union {
@@ -259,6 +262,7 @@ import "misc.idl", "security.idl";
                [case(LSA_POLICY_INFO_AUDIT_FULL_SET)]   lsa_AuditFullSetInfo   auditfullset;
                [case(LSA_POLICY_INFO_AUDIT_FULL_QUERY)] lsa_AuditFullQueryInfo auditfullquery;
                [case(LSA_POLICY_INFO_DNS)]              lsa_DnsDomainInfo      dns;
+               [case(LSA_POLICY_INFO_DNS_INT)]          lsa_DnsDomainInfo      dns;
        } lsa_PolicyInformation;
 
        NTSTATUS lsa_QueryInfoPolicy (
@@ -387,7 +391,8 @@ import "misc.idl", "security.idl";
                LSA_LOOKUP_NAMES_PRIMARY_DOMAIN_ONLY = 3,
                LSA_LOOKUP_NAMES_UPLEVEL_TRUSTS_ONLY = 4,
                LSA_LOOKUP_NAMES_FOREST_TRUSTS_ONLY = 5,
-               LSA_LOOKUP_NAMES_UPLEVEL_TRUSTS_ONLY2 = 6
+               LSA_LOOKUP_NAMES_UPLEVEL_TRUSTS_ONLY2 = 6,
+               LSA_LOOKUP_NAMES_RODC_REFERRAL_TO_FULL_DC = 7
        } lsa_LookupNamesLevel;
 
        [public] NTSTATUS lsa_LookupNames (
@@ -1008,8 +1013,8 @@ import "misc.idl", "security.idl";
                [in,out] lsa_TransSidArray2 *sids,
                [in]         lsa_LookupNamesLevel level,
                [in,out] uint32 *count,
-               [in]         uint32 unknown1,
-               [in]         uint32 unknown2
+               [in]         uint32 lookup_options,
+               [in]         uint32 client_revision /* LSA_CLIENT_REVISION* */
                );
 
        /* Function 0x3b */
@@ -1051,7 +1056,7 @@ import "misc.idl", "security.idl";
                lsa_SidType sid_type;
                dom_sid2 *sid;
                uint32 sid_index;
-               uint32 unknown;
+               uint32 flags;
        } lsa_TranslatedSid3;
 
        typedef struct {
@@ -1067,8 +1072,8 @@ import "misc.idl", "security.idl";
                [in,out] lsa_TransSidArray3 *sids,
                [in]         lsa_LookupNamesLevel level,
                [in,out] uint32 *count,
-               [in]         uint32 unknown1,
-               [in]         uint32 unknown2
+               [in]         uint32 lookup_options,
+               [in]         uint32 client_revision /* LSA_CLIENT_REVISION* */
                );
 
        /* Function 0x45 */
@@ -1147,6 +1152,11 @@ import "misc.idl", "security.idl";
                [in]         uint32 unknown2
                );
 
+       const int LSA_CLIENT_REVISION_NO_DNS     = 0x00000001;
+       const int LSA_CLIENT_REVISION_DNS        = 0x00000002;
+
+       const int LSA_LOOKUP_OPTIONS_NO_ISOLATED = 0x80000000;
+
        /* Function 0x4d */
        NTSTATUS lsa_LookupNames4(
                [in,range(0,1000)] uint32 num_names,
@@ -1155,8 +1165,8 @@ import "misc.idl", "security.idl";
                [in,out] lsa_TransSidArray3 *sids,
                [in]         lsa_LookupNamesLevel level,
                [in,out] uint32 *count,
-               [in]         uint32 unknown1,
-               [in]         uint32 unknown2
+               [in]         uint32 lookup_options,
+               [in]         uint32 client_revision /* LSA_CLIENT_REVISION* */
                );
 
        /* Function 0x4e */
index 8331977398dfe1285992f765ad93512b52e99a58..791b86466ce7f1482f7d4701cda285d0c257a185 100644 (file)
@@ -30,9 +30,11 @@ interface misc
        /* Only SEC_CHAN_WKSTA can forward requests to other domains. */
 
        typedef [public] enum {
-               SEC_CHAN_WKSTA   = 2,
-               SEC_CHAN_DOMAIN  = 4,
-               SEC_CHAN_BDC     = 6
+               SEC_CHAN_NULL        = 0,
+               SEC_CHAN_WKSTA       = 2,
+               SEC_CHAN_DNS_DOMAIN  = 3,
+               SEC_CHAN_DOMAIN      = 4,
+               SEC_CHAN_BDC         = 6
        } netr_SchannelType;
 
        /* SAM database types */
index 8a36922fdd197ef46cc8c7dc3245d199697d464b..22e90878e7279b9a1b2e7742898356e04390f850 100644 (file)
@@ -1100,6 +1100,16 @@ interface netlogon
 
        /****************/
        /* Function 0x1d */
+       typedef [bitmap32bit] bitmap {
+               NETR_TRUST_FLAG_IN_FOREST = 0x00000001,
+               NETR_TRUST_FLAG_OUTBOUND  = 0x00000002,
+               NETR_TRUST_FLAG_TREEROOT  = 0x00000004,
+               NETR_TRUST_FLAG_PRIMARY   = 0x00000008,
+               NETR_TRUST_FLAG_NATIVE    = 0x00000010,
+               NETR_TRUST_FLAG_INBOUND   = 0x00000020,
+               NETR_TRUST_FLAG_MIT_KRB5  = 0x00000080,
+               NETR_TRUST_FLAG_AES       = 0x00000100
+       } netr_TrustFlags;
 
        typedef [flag(NDR_PAHEX)] struct {
                uint16 length;
@@ -1127,26 +1137,61 @@ interface netlogon
                [case(2)] netr_DomainQuery1 *query1;
        } netr_DomainQuery;
 
+       typedef struct {
+               /* these first 3 values come from the fact windows
+                  actually encodes this structure as a UNICODE_STRING
+                  - see MS-NRPC section 2.2.1.3.9 */
+               [value(8)] uint32 length;
+               [value(0)] uint32 dummy;
+               [value(8)] uint32 size;
+               netr_TrustFlags flags;
+               uint32 parent_index;
+               uint32 trust_type;
+               uint32 trust_attributes;
+       } netr_trust_extension;
+
+       typedef struct {
+               uint16 length; /* value is 16 when info != NULL, otherwise 0 */
+               [value(length)] uint16 size;   /* value is 16 when info != NULL, otherwise 0 */
+               netr_trust_extension *info;
+       } netr_trust_extension_container;
+
        typedef struct {
                lsa_String domainname;
                lsa_String fulldomainname;
                lsa_String forest;
                GUID        guid;
                dom_sid2    *sid;
-               netr_BinaryString unknown1[4];
-               uint32      unknown[4];
+               netr_trust_extension_container trust_extension;
+               lsa_String dummystring[3];
+               uint32     dummy[4];
        } netr_DomainTrustInfo;
 
+       typedef struct {
+               uint32 policy_size;
+               [size_is(policy_size)] uint8 *policy;
+       } netr_LsaPolicyInfo;
+
+       typedef [public,bitmap32bit] bitmap {
+               NETR_WS_FLAG_HANDLES_INBOUND_TRUSTS = 0x00000001,
+               NETR_WS_FLAG_HANDLES_SPN_UPDATE     = 0x00000002
+       } netr_WorkstationFlags;
+
        typedef struct {
                netr_DomainTrustInfo domaininfo;
                uint32 num_trusts;
                [size_is(num_trusts)] netr_DomainTrustInfo *trusts;
-               uint32 unknown[14]; /* room for expansion? */
+               netr_LsaPolicyInfo lsa_policy;
+               lsa_String dns_hostname;
+               lsa_String dummystring[3];
+               netr_WorkstationFlags workstation_flags;
+               uint32 supported_enc_types;
+               uint32 dummy[2];
        } netr_DomainInfo1;
 
        typedef union {
                [case(1)] netr_DomainInfo1 *info1;
-               [case(2)] netr_DomainInfo1 *info1;
+               [case(2)] netr_DomainInfo1 *info2;
        } netr_DomainInfo;
        
        NTSTATUS netr_LogonGetDomainInfo(
@@ -1230,14 +1275,6 @@ interface netlogon
 
        /****************/
        /* Function 0x24 */
-       typedef [bitmap32bit] bitmap {
-               NETR_TRUST_FLAG_IN_FOREST = 0x00000001,
-               NETR_TRUST_FLAG_OUTBOUND  = 0x00000002,
-               NETR_TRUST_FLAG_TREEROOT  = 0x00000004,
-               NETR_TRUST_FLAG_PRIMARY   = 0x00000008,
-               NETR_TRUST_FLAG_NATIVE    = 0x00000010,
-               NETR_TRUST_FLAG_INBOUND   = 0x00000020
-       } netr_TrustFlags;
 
        typedef [v1_enum] enum {
                NETR_TRUST_TYPE_DOWNLEVEL       = 1,
index 80efe46453fb0f88cc5fb7f575f6858710644549..ac7641c0afcbe18d83e9a7a15631cf66335a263e 100644 (file)
@@ -153,6 +153,7 @@ interface security
        const string SID_CREATOR_OWNER_DOMAIN = "S-1-3";
        const string SID_CREATOR_OWNER        = "S-1-3-0";
        const string SID_CREATOR_GROUP        = "S-1-3-1";
+       const string SID_OWNER_RIGHTS         = "S-1-3-4";
 
        /* SECURITY_NT_AUTHORITY */
        const string NAME_NT_AUTHORITY            = "NT AUTHORITY";
@@ -172,9 +173,14 @@ interface security
        const string SID_NT_TERMINAL_SERVER_USERS = "S-1-5-13";
        const string SID_NT_REMOTE_INTERACTIVE    = "S-1-5-14";
        const string SID_NT_THIS_ORGANISATION     = "S-1-5-15";
+       const string SID_NT_IUSR                  = "S-1-5-17";
        const string SID_NT_SYSTEM                = "S-1-5-18";
        const string SID_NT_LOCAL_SERVICE         = "S-1-5-19";
        const string SID_NT_NETWORK_SERVICE       = "S-1-5-20";
+       const string SID_NT_DIGEST_AUTHENTICATION = "S-1-5-64-21";
+       const string SID_NT_NTLM_AUTHENTICATION   = "S-1-5-64-10";
+       const string SID_NT_SCHANNEL_AUTHENTICATION = "S-1-5-64-14";
+       const string SID_NT_OTHER_ORGANISATION    = "S-1-5-1000";
 
        /* SECURITY_BUILTIN_DOMAIN_RID */
        const string NAME_BUILTIN                  = "BUILTIN";
similarity index 82%
rename from source4/libcli/drsblobs.c
rename to source4/librpc/ndr/ndr_drsblobs.c
index 126f2ccc40ebc43e52f3baa2cd1253cf02bb61d3..aecb0c3b16bb2b5fba19e257e83de175be031590 100644 (file)
@@ -20,7 +20,7 @@
 */
 
 #include "includes.h"
-#include "libcli/drsblobs.h"
+#include "librpc/gen_ndr/ndr_drsblobs.h"
 
 /* parser auto-generated by pidl, then hand-modified by abartlet */
 
@@ -176,4 +176,38 @@ _PUBLIC_ void ndr_print_trustAuthInOutBlob(struct ndr_print *ndr, const char *na
        ndr->depth--;
 }
 
+_PUBLIC_ enum ndr_err_code ndr_pull_trustDomainPasswords(struct ndr_pull *ndr, int ndr_flags, struct trustDomainPasswords *r)
+{
+       if (ndr_flags & NDR_SCALARS) {
+               uint32_t offset;
+               NDR_PULL_ALIGN(ndr, 4);
+               NDR_PULL_NEED_BYTES(ndr, 8);
+               
+               offset = ndr->offset;
+               ndr->offset = ndr->data_size - 8;
+
+               NDR_CHECK(ndr_pull_uint32(ndr, NDR_SCALARS, &r->outgoing_size));
+               NDR_CHECK(ndr_pull_uint32(ndr, NDR_SCALARS, &r->incoming_size));
+
+               ndr->offset = offset;
+               NDR_CHECK(ndr_pull_array_uint8(ndr, NDR_SCALARS, r->confounder, 512));
+               {
+                       struct ndr_pull *_ndr_outgoing;
+                       NDR_CHECK(ndr_pull_subcontext_start(ndr, &_ndr_outgoing, 0, r->outgoing_size));
+                       NDR_CHECK(ndr_pull_trustCurrentPasswords(_ndr_outgoing, NDR_SCALARS|NDR_BUFFERS, &r->outgoing));
+                       NDR_CHECK(ndr_pull_subcontext_end(ndr, _ndr_outgoing, 0, r->outgoing_size));
+               }
+               {
+                       struct ndr_pull *_ndr_incoming;
+                       NDR_CHECK(ndr_pull_subcontext_start(ndr, &_ndr_incoming, 0, r->incoming_size));
+                       NDR_CHECK(ndr_pull_trustCurrentPasswords(_ndr_incoming, NDR_SCALARS|NDR_BUFFERS, &r->incoming));
+                       NDR_CHECK(ndr_pull_subcontext_end(ndr, _ndr_incoming, 0, r->incoming_size));
+               }
+               NDR_CHECK(ndr_pull_uint32(ndr, NDR_SCALARS, &r->outgoing_size));
+               NDR_CHECK(ndr_pull_uint32(ndr, NDR_SCALARS, &r->incoming_size));
+       }
+       if (ndr_flags & NDR_BUFFERS) {
+       }
+       return NDR_ERR_SUCCESS;
+}
 
index 5bbcc5e91c81bb4c45acedc9f4a8fede62a489f8..4e07cc7b57c89e4233da1df00f7fdca70131de8e 100644 (file)
@@ -33,9 +33,7 @@
 
 _PUBLIC_ NTSTATUS dcerpc_init(void)
 {
-       gensec_init(global_loadparm);
-
-       return NT_STATUS_OK;
+       return gensec_init(global_loadparm);
 }
 
 static void dcerpc_connection_dead(struct dcerpc_connection *conn, NTSTATUS status);
@@ -334,6 +332,7 @@ static NTSTATUS ncacn_push_request_sign(struct dcerpc_connection *c,
        DATA_BLOB creds2;
        size_t payload_length;
        enum ndr_err_code ndr_err;
+       size_t hdr_size = DCERPC_REQUEST_LENGTH;
 
        /* non-signed packets are simpler */
        if (sig_size == 0) {
@@ -367,6 +366,7 @@ static NTSTATUS ncacn_push_request_sign(struct dcerpc_connection *c,
 
        if (pkt->pfc_flags & DCERPC_PFC_FLAG_OBJECT_UUID) {
                ndr->flags |= LIBNDR_FLAG_OBJECT_PRESENT;
+               hdr_size += 16;
        }
 
        ndr_err = ndr_push_ncacn_packet(ndr, NDR_SCALARS|NDR_BUFFERS, pkt);
@@ -415,7 +415,7 @@ static NTSTATUS ncacn_push_request_sign(struct dcerpc_connection *c,
        case DCERPC_AUTH_LEVEL_PRIVACY:
                status = gensec_seal_packet(c->security_state.generic_state, 
                                            mem_ctx, 
-                                           blob->data + DCERPC_REQUEST_LENGTH, 
+                                           blob->data + hdr_size,
                                            payload_length,
                                            blob->data,
                                            blob->length,
@@ -428,7 +428,7 @@ static NTSTATUS ncacn_push_request_sign(struct dcerpc_connection *c,
        case DCERPC_AUTH_LEVEL_INTEGRITY:
                status = gensec_sign_packet(c->security_state.generic_state, 
                                            mem_ctx, 
-                                           blob->data + DCERPC_REQUEST_LENGTH, 
+                                           blob->data + hdr_size,
                                            payload_length, 
                                            blob->data,
                                            blob->length,
index 318b8fe36d19cf78a49435ccc85657cbbcb62ddb..b117a98270a1f912e006c8be92284d51395900ed 100644 (file)
@@ -121,6 +121,7 @@ static struct composite_context *dcerpc_pipe_connect_ncacn_np_smb_send(TALLOC_CT
        conn->in.workgroup              = lp_workgroup(lp_ctx);
 
        lp_smbcli_options(lp_ctx, &conn->in.options);
+       lp_smbcli_session_options(lp_ctx, &conn->in.session_options);
 
        /*
         * provide proper credentials - user supplied, but allow a
@@ -137,7 +138,7 @@ static struct composite_context *dcerpc_pipe_connect_ncacn_np_smb_send(TALLOC_CT
 
        /* send smb connect request */
        conn_req = smb_composite_connect_send(conn, s->io.pipe->conn, 
-                                             lp_resolve_context(lp_ctx), 
+                                             s->io.resolve_ctx,
                                              s->io.pipe->conn->event_ctx);
        if (composite_nomem(conn_req, c)) return c;
 
index abc67ad38bb4d63625889dedab65065b75439393..b4d5d05b617407432a4e6658183afad301f63107 100644 (file)
@@ -95,13 +95,14 @@ _PUBLIC_ struct composite_context* dcerpc_secondary_connection_send(struct dcerp
                                                         s->binding->host,
                                                         s->binding->target_hostname,
                                                         atoi(s->binding->endpoint),
-                                                        lp_resolve_context(global_loadparm));
+                                                        dcerpc_resolve_ctx(s->pipe->conn));
                composite_continue(c, pipe_tcp_req, continue_open_tcp, c);
                return c;
 
        case NCALRPC:
-               pipe_ncalrpc_req = dcerpc_pipe_open_pipe_send(s->pipe2->conn, lp_ncalrpc_dir(global_loadparm), 
-                                                             s->binding->endpoint);
+       case NCACN_UNIX_STREAM:
+               pipe_ncalrpc_req = dcerpc_pipe_open_unix_stream_send(s->pipe2->conn, 
+                                                             dcerpc_unix_socket_path(s->pipe->conn));
                composite_continue(c, pipe_ncalrpc_req, continue_open_pipe, c);
                return c;
 
index 7480beae33eab4428d18f2eb29aaa21df531fc8e..1e2b4cde484769a8ee375d72185a2686178b0090 100644 (file)
@@ -39,6 +39,9 @@ struct sock_private {
 
        struct packet_context *packet;
        uint32_t pending_reads;
+
+       struct resolve_context *resolve_ctx;
+       const char *path; /* For ncacn_unix_sock and ncalrpc */
 };
 
 
@@ -307,6 +310,7 @@ static struct composite_context *dcerpc_pipe_open_socket_send(TALLOC_CTX *mem_ct
                                                       struct resolve_context *resolve_context,
                                                       struct socket_address *server,
                                                       const char *target_hostname,
+                                                      const char *full_path,
                                                       enum dcerpc_transport_t transport)
 {
        struct composite_context *c;
@@ -334,6 +338,9 @@ static struct composite_context *dcerpc_pipe_open_socket_send(TALLOC_CTX *mem_ct
 
        talloc_steal(s->sock, s->socket_ctx);
 
+       s->sock->resolve_ctx = resolve_context;
+       s->sock->path = talloc_reference(s->sock, full_path);
+
        conn_req = socket_connect_send(s->socket_ctx, NULL, s->server, 0, 
                                       resolve_context, 
                                       c->event_ctx);
@@ -386,6 +393,7 @@ static void continue_ip_resolve_name(struct composite_context *ctx)
        sock_ipv4_req = dcerpc_pipe_open_socket_send(c, s->conn,
                                                     s->resolve_ctx,
                                                     s->srvaddr, s->target_hostname,
+                                                    NULL,
                                                     NCACN_IP_TCP);
        composite_continue(c, sock_ipv4_req, continue_ipv4_open_socket, c);
 }
@@ -561,6 +569,7 @@ struct composite_context *dcerpc_pipe_open_unix_stream_send(struct dcerpc_connec
        sock_unix_req = dcerpc_pipe_open_socket_send(c, s->conn, 
                                                     NULL,
                                                     s->srvaddr, NULL,
+                                                    s->path,
                                                     NCALRPC);
        composite_continue(c, sock_unix_req, continue_unix_open_socket, c);
        return c;
@@ -579,13 +588,6 @@ NTSTATUS dcerpc_pipe_open_unix_stream_recv(struct composite_context *c)
 }
 
 
-struct pipe_np_state {
-       char *full_path;
-       struct socket_address *srvaddr;
-       struct dcerpc_connection *conn;
-};
-
-
 /*
   Stage 2 of dcerpc_pipe_open_pipe_send: receive socket open request
 */
@@ -612,13 +614,13 @@ struct composite_context* dcerpc_pipe_open_pipe_send(struct dcerpc_connection *c
 
        struct composite_context *c;
        struct composite_context *sock_np_req;
-       struct pipe_np_state *s;
+       struct pipe_unix_state *s;
 
        /* composite context allocation and setup */
        c = composite_create(conn, conn->event_ctx);
        if (c == NULL) return NULL;
 
-       s = talloc_zero(c, struct pipe_np_state);
+       s = talloc_zero(c, struct pipe_unix_state);
        if (composite_nomem(s, c)) return c;
        c->private_data = s;
 
@@ -628,15 +630,15 @@ struct composite_context* dcerpc_pipe_open_pipe_send(struct dcerpc_connection *c
        s->conn = conn;
 
        string_replace(canon, '/', '\\');
-       s->full_path = talloc_asprintf(canon, "%s/%s", ncalrpc_dir, canon);
-       if (composite_nomem(s->full_path, c)) return c;
+       s->path = talloc_asprintf(canon, "%s/%s", ncalrpc_dir, canon);
+       if (composite_nomem(s->path, c)) return c;
 
        /* prepare server address using path and transport name */
-       s->srvaddr = socket_address_from_strings(conn, "unix", s->full_path, 0);
+       s->srvaddr = socket_address_from_strings(conn, "unix", s->path, 0);
        if (composite_nomem(s->srvaddr, c)) return c;
 
        /* send socket open request */
-       sock_np_req = dcerpc_pipe_open_socket_send(c, s->conn, NULL, s->srvaddr, NULL, NCALRPC);
+       sock_np_req = dcerpc_pipe_open_socket_send(c, s->conn, NULL, s->srvaddr, NULL, s->path, NCALRPC);
        composite_continue(c, sock_np_req, continue_np_open_socket, c);
        return c;
 }
@@ -662,3 +664,15 @@ NTSTATUS dcerpc_pipe_open_pipe(struct dcerpc_connection *conn, const char *ncalr
        struct composite_context *c = dcerpc_pipe_open_pipe_send(conn, ncalrpc_dir, identifier);
        return dcerpc_pipe_open_pipe_recv(c);
 }
+
+const char *dcerpc_unix_socket_path(struct dcerpc_connection *p)
+{
+       struct sock_private *sock = (struct sock_private *)p->transport.private_data;
+       return sock->path;
+}
+
+struct resolve_context *dcerpc_resolve_ctx(struct dcerpc_connection *p)
+{
+       struct sock_private *sock = (struct sock_private *)p->transport.private_data;
+       return sock->resolve_ctx;
+}
index 5e95270b7d2f8f01960b552055748fd308dd454f..1bc3e2b62fd63f7b260ec1549111719f95ec6cc2 100644 (file)
@@ -77,7 +77,7 @@ static void nbtd_netlogon_getdc(struct dgram_mailslot_handler *dgmslot,
        /* setup a GETDC reply */
        ZERO_STRUCT(netlogon_response);
        netlogon_response.response_type = NETLOGON_GET_PDC;
-       pdc = &netlogon_response.get_pdc;
+       pdc = &netlogon_response.data.get_pdc;
 
        pdc->command = NETLOGON_RESPONSE_FROM_PDC;
        pdc->pdc_name         = lp_netbios_name(iface->nbtsrv->task->lp_ctx);
@@ -132,7 +132,7 @@ static void nbtd_netlogon_samlogon(struct dgram_mailslot_handler *dgmslot,
 
        status = fill_netlogon_samlogon_response(samctx, packet, NULL, name->name, sid, NULL, 
                                                 netlogon->req.logon.user_name, netlogon->req.logon.acct_control, src->addr, 
-                                                netlogon->req.logon.nt_version, iface->nbtsrv->task->lp_ctx, &netlogon_response.samlogon);
+                                                netlogon->req.logon.nt_version, iface->nbtsrv->task->lp_ctx, &netlogon_response.data.samlogon);
        if (!NT_STATUS_IS_OK(status)) {
                DEBUG(2,("NBT netlogon query failed domain=%s sid=%s version=%d - %s\n",
                         name->name, dom_sid_string(packet, sid), netlogon->req.logon.nt_version, nt_errstr(status)));
index 8f1f74afcf2bfe1d391c077fb78d8ac7e60b7eb7..fc61372ead8377b7be865f286fe75e0b3c267d52 100644 (file)
@@ -79,16 +79,17 @@ static void getdc_recv_netlogon_reply(struct dgram_mailslot_handler *dgmslot,
 
        /* We asked for version 1 only */
        if (netlogon.response_type == NETLOGON_SAMLOGON
-           && netlogon.samlogon.ntver != NETLOGON_NT_VERSION_1) {
+           && netlogon.data.samlogon.ntver != NETLOGON_NT_VERSION_1) {
                status = NT_STATUS_INVALID_NETWORK_RESPONSE;
                goto done;
        }
 
-       p = netlogon.samlogon.nt4.server;
+       p = netlogon.data.samlogon.data.nt4.server;
 
        DEBUG(10, ("NTLOGON_SAM_LOGON_REPLY: server: %s, user: %s, "
-                  "domain: %s\n", p, netlogon.samlogon.nt4.user_name,
-                  netlogon.samlogon.nt4.domain));
+                  "domain: %s\n", p,
+                  netlogon.data.samlogon.data.nt4.user_name,
+                  netlogon.data.samlogon.data.nt4.domain));
 
        if (*p == '\\') p += 1;
        if (*p == '\\') p += 1;
index 844fa11cc5f584df597b0c791386b07354d08c98..9bc36a176266d61510db9cc668b51ae946681faf 100644 (file)
@@ -206,6 +206,7 @@ static NTSTATUS cvfs_connect(struct ntvfs_module_context *ntvfs,
        io.in.service = remote_share;
        io.in.service_type = "?????";
        lp_smbcli_options(ntvfs->ctx->lp_ctx, &io.in.options);
+       lp_smbcli_session_options(ntvfs->ctx->lp_ctx, &io.in.session_options);
 
        if (!(ntvfs->ctx->client_caps & NTVFS_CLIENT_CAP_LEVEL_II_OPLOCKS)) {
                io.in.options.use_level2_oplocks = false;
index 57a463aba6d8a485ce9b7f56b58363585a4dd86b..d479f1e2ee0e452ec48243d3a6db4ec7d9e14a68 100644 (file)
@@ -511,6 +511,12 @@ NTSTATUS pvfs_access_check(struct pvfs_state *pvfs,
        NTSTATUS status;
        struct security_descriptor *sd;
 
+       /* on SMB2 a blank access mask is always denied */
+       if (pvfs->ntvfs->ctx->protocol == PROTOCOL_SMB2 &&
+           *access_mask == 0) {
+               return NT_STATUS_ACCESS_DENIED;
+       }
+
        if (pvfs_read_only(pvfs, *access_mask)) {
                return NT_STATUS_ACCESS_DENIED;
        }
index 15edbd1f89c737239ffb71f38be03724e88f7559..0042dbd876b80738a3f867118826a66b28d7dcbf 100644 (file)
@@ -2629,3 +2629,11 @@ void lp_smbcli_options(struct loadparm_context *lp_ctx,
        options->use_oplocks = true;
        options->use_level2_oplocks = true;
 }
+
+void lp_smbcli_session_options(struct loadparm_context *lp_ctx,
+                                struct smbcli_session_options *options)
+{
+       options->lanman_auth = lp_client_lanman_auth(lp_ctx);
+       options->ntlmv2_auth = lp_client_ntlmv2_auth(lp_ctx);
+       options->plaintext_auth = lp_client_plaintext_auth(lp_ctx);
+}
index 4ed2654692ea6dbff3b039cb60a797686b3a977f..4c6e8b79a2283eabed1ed18ef3833445f04d6a22 100644 (file)
@@ -60,6 +60,7 @@ enum announce_as {/* Types of machine we can announce as. */
 struct loadparm_context;
 struct loadparm_service;
 struct smbcli_options;
+struct smbcli_session_options;
 
 void reload_charcnv(struct loadparm_context *lp_ctx);
 
@@ -318,6 +319,8 @@ int lp_maxprintjobs(struct loadparm_service *service, struct loadparm_service *s
 struct smb_iconv_convenience *lp_iconv_convenience(struct loadparm_context *lp_ctx);
 void lp_smbcli_options(struct loadparm_context *lp_ctx,
                         struct smbcli_options *options);
+void lp_smbcli_session_options(struct loadparm_context *lp_ctx,
+                                struct smbcli_session_options *options);
 
 /* The following definitions come from param/generic.c  */
 
index e5f59d0cf946c65dcdb6638fda6a122115034931..893055d3b1ad70f078b2541edc38acccdaa174e2 100644 (file)
@@ -870,10 +870,6 @@ static NTSTATUS dcesrv_request(struct dcesrv_call_state *call)
        call->context   = context;
        call->ndr_pull  = pull;
 
-       if (call->pkt.pfc_flags & DCERPC_PFC_FLAG_OBJECT_UUID) {
-               pull->flags |= LIBNDR_FLAG_OBJECT_PRESENT;
-       }
-
        if (!(call->pkt.drep[0] & DCERPC_DREP_LE)) {
                pull->flags |= LIBNDR_FLAG_BIGENDIAN;
        }
@@ -1112,6 +1108,10 @@ NTSTATUS dcesrv_input_process(struct dcesrv_connection *dce_conn)
                ndr->flags |= LIBNDR_FLAG_BIGENDIAN;
        }
 
+       if (CVAL(blob.data, DCERPC_PFC_OFFSET) & DCERPC_PFC_FLAG_OBJECT_UUID) {
+               ndr->flags |= LIBNDR_FLAG_OBJECT_PRESENT;
+       }
+
        ndr_err = ndr_pull_ncacn_packet(ndr, NDR_SCALARS|NDR_BUFFERS, &call->pkt);
        if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
                talloc_free(dce_conn->partial_input.data);
index 16bf4eb7ed9bf8c6ef04356e106fe8939bd951a8..bef7e4be78134b94967ffa67a9a95e053fc2c2db 100644 (file)
@@ -95,6 +95,10 @@ bool dcesrv_auth_bind(struct dcesrv_call_state *call)
                return false;
        }
 
+       if (call->conn->state_flags & DCESRV_CALL_STATE_FLAG_HEADER_SIGNING) {
+               gensec_want_feature(auth->gensec_security, GENSEC_FEATURE_SIGN_PKT_HEADER);
+       }
+
        return true;
 }
 
@@ -287,6 +291,7 @@ bool dcesrv_auth_request(struct dcesrv_call_state *call, DATA_BLOB *full_packet)
        struct ndr_pull *ndr;
        NTSTATUS status;
        enum ndr_err_code ndr_err;
+       size_t hdr_size = DCERPC_REQUEST_LENGTH;
 
        if (!dce_conn->auth_state.auth_info ||
            !dce_conn->auth_state.gensec_security) {
@@ -335,6 +340,11 @@ bool dcesrv_auth_request(struct dcesrv_call_state *call, DATA_BLOB *full_packet)
                ndr->flags |= LIBNDR_FLAG_BIGENDIAN;
        }
 
+       if (pkt->pfc_flags & DCERPC_PFC_FLAG_OBJECT_UUID) {
+               ndr->flags |= LIBNDR_FLAG_OBJECT_PRESENT;
+               hdr_size += 16;
+       }
+
        ndr_err = ndr_pull_dcerpc_auth(ndr, NDR_SCALARS|NDR_BUFFERS, &auth);
        if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
                talloc_free(ndr);
@@ -346,13 +356,13 @@ bool dcesrv_auth_request(struct dcesrv_call_state *call, DATA_BLOB *full_packet)
        case DCERPC_AUTH_LEVEL_PRIVACY:
                status = gensec_unseal_packet(dce_conn->auth_state.gensec_security,
                                              call,
-                                             full_packet->data + DCERPC_REQUEST_LENGTH,
+                                             full_packet->data + hdr_size,
                                              pkt->u.request.stub_and_verifier.length, 
                                              full_packet->data,
                                              full_packet->length-auth.credentials.length,
                                              &auth.credentials);
                memcpy(pkt->u.request.stub_and_verifier.data, 
-                      full_packet->data + DCERPC_REQUEST_LENGTH,
+                      full_packet->data + hdr_size,
                       pkt->u.request.stub_and_verifier.length);
                break;
 
index 47174b6eeb8b942eb253596eb8eb029a3ecf83f7..4831fb063da91551f847ac2af496fce4fe034f41 100644 (file)
@@ -29,7 +29,6 @@
 static int dcesrv_handle_destructor(struct dcesrv_handle *h)
 {
        DLIST_REMOVE(h->context->handles, h);
-       talloc_free(h);
        return 0;
 }
 
index 3b70f3e93460fca9ba145ce90b9e63a6e3bf47c4..836fd8dc621645a7a8939b5d80658387b7d609f3 100644 (file)
@@ -1,3 +1,5 @@
+/* need access mask/acl implementation */
+
 /* 
    Unix SMB/CIFS implementation.
 
@@ -141,7 +143,8 @@ static NTSTATUS dcesrv_lsa_DeleteObject(struct dcesrv_call_state *dce_call, TALL
 
                return NT_STATUS_OK;
        } else if (h->wire_handle.handle_type == LSA_HANDLE_TRUSTED_DOMAIN) {
-               struct lsa_trusted_domain_state *trusted_domain_state = h->data;
+               struct lsa_trusted_domain_state *trusted_domain_state = 
+                       talloc_get_type(h->data, struct lsa_trusted_domain_state);
                ret = ldb_transaction_start(trusted_domain_state->policy->sam_ldb);
                if (ret != 0) {
                        return NT_STATUS_INTERNAL_DB_CORRUPTION;
@@ -187,6 +190,9 @@ static NTSTATUS dcesrv_lsa_DeleteObject(struct dcesrv_call_state *dce_call, TALL
                r2.in.sid = astate->account_sid;
                r2.out.rights = rights;
 
+               /* dcesrv_lsa_EnumAccountRights takes a LSA_HANDLE_POLICY,
+                  but we have a LSA_HANDLE_ACCOUNT here, so this call
+                  will always fail */
                status = dcesrv_lsa_EnumAccountRights(dce_call, mem_ctx, &r2);
                if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
                        return NT_STATUS_OK;
@@ -444,18 +450,46 @@ static NTSTATUS dcesrv_lsa_QueryInfoPolicy2(struct dcesrv_call_state *dce_call,
        ZERO_STRUCTP(r->out.info);
 
        switch (r->in.level) {
+       case LSA_POLICY_INFO_AUDIT_LOG:
+               /* we don't need to fill in any of this */
+               ZERO_STRUCT(r->out.info->audit_log);
+               return NT_STATUS_OK;
+       case LSA_POLICY_INFO_AUDIT_EVENTS:
+               /* we don't need to fill in any of this */
+               ZERO_STRUCT(r->out.info->audit_events);
+               return NT_STATUS_OK;
+       case LSA_POLICY_INFO_PD:
+               /* we don't need to fill in any of this */
+               ZERO_STRUCT(r->out.info->pd);
+               return NT_STATUS_OK;
        case LSA_POLICY_INFO_DOMAIN:
        case LSA_POLICY_INFO_ACCOUNT_DOMAIN:
                return dcesrv_lsa_info_AccountDomain(state, mem_ctx, &r->out.info->account_domain);
+       case LSA_POLICY_INFO_ROLE:
+               r->out.info->role.role = LSA_ROLE_PRIMARY;
+               return NT_STATUS_OK;
 
        case LSA_POLICY_INFO_DNS:
+       case LSA_POLICY_INFO_DNS_INT:
                return dcesrv_lsa_info_DNS(state, mem_ctx, &r->out.info->dns);
-       case LSA_POLICY_INFO_DB:
+
+       case LSA_POLICY_INFO_REPLICA:
+               ZERO_STRUCT(r->out.info->replica);
+               return NT_STATUS_OK;
+
+       case LSA_POLICY_INFO_QUOTA:
+               ZERO_STRUCT(r->out.info->quota);
+               return NT_STATUS_OK;
+
        case LSA_POLICY_INFO_AUDIT_FULL_SET:
+       case LSA_POLICY_INFO_DB:
        case LSA_POLICY_INFO_AUDIT_FULL_QUERY:
+               /* windows gives INVALID_PARAMETER */
+               r->out.info = NULL;
                return NT_STATUS_INVALID_PARAMETER;
        }
 
+       r->out.info = NULL;
        return NT_STATUS_INVALID_INFO_CLASS;
 }
 
@@ -468,6 +502,8 @@ static NTSTATUS dcesrv_lsa_QueryInfoPolicy(struct dcesrv_call_state *dce_call, T
        struct lsa_QueryInfoPolicy2 r2;
        NTSTATUS status;
 
+       ZERO_STRUCT(r2);
+
        r2.in.handle = r->in.handle;
        r2.in.level = r->in.level;
        
@@ -484,6 +520,7 @@ static NTSTATUS dcesrv_lsa_QueryInfoPolicy(struct dcesrv_call_state *dce_call, T
 static NTSTATUS dcesrv_lsa_SetInfoPolicy(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
                                  struct lsa_SetInfoPolicy *r)
 {
+       /* need to support this */
        DCESRV_FAULT(DCERPC_FAULT_OP_RNG_ERROR);
 }
 
@@ -502,6 +539,13 @@ static NTSTATUS dcesrv_lsa_ClearAuditLog(struct dcesrv_call_state *dce_call, TAL
   lsa_CreateAccount 
 
   This call does not seem to have any long-term effects, hence no database operations
+
+  we need to talk to the MS product group to find out what this account database means!
+
+  answer is that the lsa database is totally separate from the SAM and
+  ldap databases. We are going to need a separate ldb to store these
+  accounts. The SIDs on this account bear no relation to the SIDs in
+  AD
 */
 static NTSTATUS dcesrv_lsa_CreateAccount(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
                                  struct lsa_CreateAccount *r)
@@ -626,7 +670,7 @@ static NTSTATUS dcesrv_lsa_CreateTrustedDomain_base(struct dcesrv_call_state *dc
        const char *name;
        DATA_BLOB session_key = data_blob(NULL, 0);
        DATA_BLOB trustAuthIncoming, trustAuthOutgoing, auth_blob;
-       struct trustAuthInAndOutBlob auth_struct;
+       struct trustDomainPasswords auth_struct;
        int ret;
        NTSTATUS nt_status;
        enum ndr_err_code ndr_err;
@@ -648,7 +692,7 @@ static NTSTATUS dcesrv_lsa_CreateTrustedDomain_base(struct dcesrv_call_state *dc
        
        dns_name = r->in.info->domain_name.string;
        
-       trusted_domain_state = talloc(mem_ctx, struct lsa_trusted_domain_state);
+       trusted_domain_state = talloc_zero(mem_ctx, struct lsa_trusted_domain_state);
        if (!trusted_domain_state) {
                return NT_STATUS_NO_MEMORY;
        }
@@ -679,16 +723,49 @@ static NTSTATUS dcesrv_lsa_CreateTrustedDomain_base(struct dcesrv_call_state *dc
                ndr_err = ndr_pull_struct_blob(&auth_blob, mem_ctx, 
                                               lp_iconv_convenience(dce_call->conn->dce_ctx->lp_ctx),
                                               &auth_struct,
-                                              (ndr_pull_flags_fn_t)ndr_pull_trustAuthInAndOutBlob);
+                                              (ndr_pull_flags_fn_t)ndr_pull_trustDomainPasswords);
                if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
                        return NT_STATUS_INVALID_PARAMETER;
                }                               
+
+               if (op == NDR_LSA_CREATETRUSTEDDOMAINEX) {
+                       if (auth_struct.incoming.count > 1) {
+                               return NT_STATUS_INVALID_PARAMETER;
+                       }
+               }
        }
 
        if (auth_struct.incoming.count) {
+               int i;
+               struct trustAuthInOutBlob incoming;
+               
+               incoming.count = auth_struct.incoming.count;
+               incoming.current = talloc(mem_ctx, struct AuthenticationInformationArray);
+               if (!incoming.current) {
+                       return NT_STATUS_NO_MEMORY;
+               }
+               
+               incoming.current->array = *auth_struct.incoming.current;
+               if (!incoming.current->array) {
+                       return NT_STATUS_NO_MEMORY;
+               }
+
+               incoming.previous = talloc(mem_ctx, struct AuthenticationInformationArray);
+               if (!incoming.previous) {
+                       return NT_STATUS_NO_MEMORY;
+               }
+               incoming.previous->array = talloc_array(mem_ctx, struct AuthenticationInformation, incoming.count);
+               if (!incoming.previous->array) {
+                       return NT_STATUS_NO_MEMORY;
+               }
+
+               for (i = 0; i < incoming.count; i++) {
+                       incoming.previous->array[i].LastUpdateTime = 0;
+                       incoming.previous->array[i].AuthType = 0;
+               }
                ndr_err = ndr_push_struct_blob(&trustAuthIncoming, mem_ctx, 
                                               lp_iconv_convenience(dce_call->conn->dce_ctx->lp_ctx),
-                                              &auth_struct.incoming,
+                                              &incoming,
                                               (ndr_push_flags_fn_t)ndr_push_trustAuthInOutBlob);
                if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
                        return NT_STATUS_INVALID_PARAMETER;
@@ -698,9 +775,36 @@ static NTSTATUS dcesrv_lsa_CreateTrustedDomain_base(struct dcesrv_call_state *dc
        }
        
        if (auth_struct.outgoing.count) {
+               int i;
+               struct trustAuthInOutBlob outgoing;
+               
+               outgoing.count = auth_struct.outgoing.count;
+               outgoing.current = talloc(mem_ctx, struct AuthenticationInformationArray);
+               if (!outgoing.current) {
+                       return NT_STATUS_NO_MEMORY;
+               }
+               
+               outgoing.current->array = *auth_struct.outgoing.current;
+               if (!outgoing.current->array) {
+                       return NT_STATUS_NO_MEMORY;
+               }
+
+               outgoing.previous = talloc(mem_ctx, struct AuthenticationInformationArray);
+               if (!outgoing.previous) {
+                       return NT_STATUS_NO_MEMORY;
+               }
+               outgoing.previous->array = talloc_array(mem_ctx, struct AuthenticationInformation, outgoing.count);
+               if (!outgoing.previous->array) {
+                       return NT_STATUS_NO_MEMORY;
+               }
+
+               for (i = 0; i < outgoing.count; i++) {
+                       outgoing.previous->array[i].LastUpdateTime = 0;
+                       outgoing.previous->array[i].AuthType = 0;
+               }
                ndr_err = ndr_push_struct_blob(&trustAuthOutgoing, mem_ctx, 
                                               lp_iconv_convenience(dce_call->conn->dce_ctx->lp_ctx),
-                                              &auth_struct.outgoing,
+                                              &outgoing,
                                               (ndr_push_flags_fn_t)ndr_push_trustAuthInOutBlob);
                if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
                        return NT_STATUS_INVALID_PARAMETER;
@@ -859,11 +963,11 @@ static NTSTATUS dcesrv_lsa_CreateTrustedDomain_base(struct dcesrv_call_state *dc
                if (auth_struct.incoming.count) {
                        int i;
                        for (i=0; i < auth_struct.incoming.count; i++ ) {
-                               if (auth_struct.incoming.current->array[i].AuthType == TRUST_AUTH_TYPE_NT4OWF) {
+                               if (auth_struct.incoming.current[i]->AuthType == TRUST_AUTH_TYPE_NT4OWF) {
                                        samdb_msg_add_hash(trusted_domain_state->policy->sam_ldb, 
                                                           mem_ctx, msg_user, "unicodePwd", 
-                                                          &auth_struct.incoming.current->array[i].AuthInfo.nt4owf.password);
-                               } else if (auth_struct.incoming.current->array[i].AuthType == TRUST_AUTH_TYPE_CLEAR) {
+                                                          &auth_struct.incoming.current[i]->AuthInfo.nt4owf.password);
+                               } else if (auth_struct.incoming.current[i]->AuthType == TRUST_AUTH_TYPE_CLEAR) {
                                        struct samr_Password hash;
 /*
                                       . We cannot do this, as windows chooses to send in random passwords here, that won't convert to UTF8 
@@ -871,8 +975,8 @@ static NTSTATUS dcesrv_lsa_CreateTrustedDomain_base(struct dcesrv_call_state *dc
                                                             mem_ctx, msg_user, "userPassword", 
                                                             auth_struct.incoming.current->array[i].AuthInfo.clear.password);
 */
-                                       mdfour(hash.hash, auth_struct.incoming.current->array[i].AuthInfo.clear.password,
-                                              auth_struct.incoming.current->array[i].AuthInfo.clear.size);
+                                       mdfour(hash.hash, auth_struct.incoming.current[i]->AuthInfo.clear.password,
+                                              auth_struct.incoming.current[i]->AuthInfo.clear.size);
                                        samdb_msg_add_hash(trusted_domain_state->policy->sam_ldb, 
                                                           mem_ctx, msg_user, "unicodePwd", 
                                                           &hash);
@@ -1004,7 +1108,7 @@ static NTSTATUS dcesrv_lsa_OpenTrustedDomain(struct dcesrv_call_state *dce_call,
        ZERO_STRUCTP(r->out.trustdom_handle);
        policy_state = policy_handle->data;
 
-       trusted_domain_state = talloc(mem_ctx, struct lsa_trusted_domain_state);
+       trusted_domain_state = talloc_zero(mem_ctx, struct lsa_trusted_domain_state);
        if (!trusted_domain_state) {
                return NT_STATUS_NO_MEMORY;
        }
@@ -1088,7 +1192,7 @@ static NTSTATUS dcesrv_lsa_OpenTrustedDomainByName(struct dcesrv_call_state *dce
                return NT_STATUS_INVALID_PARAMETER;
        }
        
-       trusted_domain_state = talloc(mem_ctx, struct lsa_trusted_domain_state);
+       trusted_domain_state = talloc_zero(mem_ctx, struct lsa_trusted_domain_state);
        if (!trusted_domain_state) {
                return NT_STATUS_NO_MEMORY;
        }
@@ -1228,7 +1332,7 @@ static NTSTATUS dcesrv_lsa_QueryTrustedDomainInfo(struct dcesrv_call_state *dce_
 
        DCESRV_PULL_HANDLE(h, r->in.trustdom_handle, LSA_HANDLE_TRUSTED_DOMAIN);
 
-       trusted_domain_state = h->data;
+       trusted_domain_state = talloc_get_type(h->data, struct lsa_trusted_domain_state);
 
        /* pull all the user attributes */
        ret = gendb_search_dn(trusted_domain_state->policy->sam_ldb, mem_ctx,
@@ -2786,6 +2890,7 @@ static NTSTATUS dcesrv_lsa_SetInfoPolicy2(struct dcesrv_call_state *dce_call,
                                   TALLOC_CTX *mem_ctx,
                                   struct lsa_SetInfoPolicy2 *r)
 {
+       /* need to support these */
        DCESRV_FAULT(DCERPC_FAULT_OP_RNG_ERROR);
 }
 
index e5e31c74f8331c65932c6160d4bbd66ed2ccbc63..8d8417109f8de0b008bf82494e7f3842abfc98b1 100644 (file)
@@ -199,6 +199,12 @@ NTSTATUS dcesrv_lsa_OpenPolicy2(struct dcesrv_call_state *dce_call, TALLOC_CTX *
 
        ZERO_STRUCTP(r->out.handle);
 
+       if (r->in.attr != NULL &&
+           r->in.attr->root_dir != NULL) {
+               /* MS-LSAD 3.1.4.4.1 */
+               return NT_STATUS_INVALID_PARAMETER;
+       }
+
        status = dcesrv_lsa_get_policy_state(dce_call, mem_ctx, &state);
        if (!NT_STATUS_IS_OK(status)) {
                return status;
@@ -211,6 +217,8 @@ NTSTATUS dcesrv_lsa_OpenPolicy2(struct dcesrv_call_state *dce_call, TALLOC_CTX *
 
        handle->data = talloc_steal(handle, state);
 
+       /* need to check the access mask against - need ACLs - fails
+          WSPP test */
        state->access_mask = r->in.access_mask;
        state->handle = handle;
        *r->out.handle = handle->wire_handle;
index 30bceb813903059fd9620ffb1f529fdd48127870..2375a6d27aa9ea2343d0ce92f08753bd9d8b1d19 100644 (file)
@@ -43,6 +43,11 @@ static const struct {
                .sid = SID_CREATOR_GROUP,
                .rtype = SID_NAME_WKN_GRP,
        },
+       {
+               .name = "Owner Rights",
+               .sid = SID_OWNER_RIGHTS,
+               .rtype = SID_NAME_WKN_GRP,
+       },
        {
                .domain = "NT AUTHORITY",
                .name = "Dialup",
@@ -111,7 +116,7 @@ static const struct {
        },
        {
                .domain = "NT AUTHORITY",
-               .name = "Termainal Server User",
+               .name = "Terminal Server User",
                .sid = SID_NT_TERMINAL_SERVER_USERS,
                .rtype = SID_NAME_WKN_GRP,
        },
@@ -145,6 +150,42 @@ static const struct {
                .sid = SID_NT_NETWORK_SERVICE,
                .rtype = SID_NAME_WKN_GRP,
        },
+       {
+               .domain = "NT AUTHORITY",
+               .name = "Digest Authentication",
+               .sid = SID_NT_DIGEST_AUTHENTICATION,
+               .rtype = SID_NAME_WKN_GRP,
+       },
+       {
+               .domain = "NT AUTHORITY",
+               .name = "Enterprise Domain Controllers",
+               .sid = SID_NT_ENTERPRISE_DCS,
+               .rtype = SID_NAME_WKN_GRP,
+       },
+       {
+               .domain = "NT AUTHORITY",
+               .name = "NTLM Authentication",
+               .sid = SID_NT_NTLM_AUTHENTICATION,
+               .rtype = SID_NAME_WKN_GRP,
+       },
+       {
+               .domain = "NT AUTHORITY",
+               .name = "Other Organization",
+               .sid = SID_NT_OTHER_ORGANISATION,
+               .rtype = SID_NAME_WKN_GRP,
+       },
+       {
+               .domain = "NT AUTHORITY",
+               .name = "SChannel Authentication",
+               .sid = SID_NT_SCHANNEL_AUTHENTICATION,
+               .rtype = SID_NAME_WKN_GRP,
+       },
+       {
+               .domain = "NT AUTHORITY",
+               .name = "IUSR",
+               .sid = SID_NT_IUSR,
+               .rtype = SID_NAME_WKN_GRP,
+       },
        {
                .sid = NULL,
        }
@@ -484,8 +525,19 @@ NTSTATUS dcesrv_lsa_LookupSids2(struct dcesrv_call_state *dce_call,
        int i;
        NTSTATUS status = NT_STATUS_OK;
 
+       if (r->in.level < LSA_LOOKUP_NAMES_ALL ||
+           r->in.level > LSA_LOOKUP_NAMES_RODC_REFERRAL_TO_FULL_DC) {
+               return NT_STATUS_INVALID_PARAMETER;
+       }
+
        r->out.domains = NULL;
 
+       /* NOTE: the WSPP test suite tries SIDs with invalid revision numbers,
+          and expects NT_STATUS_INVALID_PARAMETER back - we just treat it as 
+          an unknown SID. We could add a SID validator here. (tridge) 
+          MS-DTYP 2.4.2
+       */
+
        status = dcesrv_lsa_get_policy_state(dce_call, mem_ctx, &state);
        if (!NT_STATUS_IS_OK(status)) {
                return status;
@@ -542,7 +594,7 @@ NTSTATUS dcesrv_lsa_LookupSids2(struct dcesrv_call_state *dce_call,
                                                    authority_name, sid, 
                                                    r->out.domains, &sid_index);
                if (!NT_STATUS_IS_OK(status2)) {
-                       return status2;
+                       continue;
                }
 
                r->out.names->names[i].sid_type    = rtype;
@@ -579,6 +631,8 @@ NTSTATUS dcesrv_lsa_LookupSids3(struct dcesrv_call_state *dce_call,
        NTSTATUS status;
        struct dcesrv_handle *h;
 
+       ZERO_STRUCT(r2);
+       
        /* No policy handle on the wire, so make one up here */
        r2.in.handle = talloc(mem_ctx, struct policy_handle);
        if (!r2.in.handle) {
@@ -608,9 +662,6 @@ NTSTATUS dcesrv_lsa_LookupSids3(struct dcesrv_call_state *dce_call,
        r2.out.names   = r->out.names;
 
        status = dcesrv_lsa_LookupSids2(dce_call, mem_ctx, &r2);
-       if (dce_call->fault_code != 0) {
-               return status;
-       }
 
        r->out.domains = r2.out.domains;
        r->out.names   = r2.out.names;
@@ -630,6 +681,8 @@ NTSTATUS dcesrv_lsa_LookupSids(struct dcesrv_call_state *dce_call, TALLOC_CTX *m
        NTSTATUS status;
        int i;
 
+       ZERO_STRUCT(r2);
+
        r2.in.handle   = r->in.handle;
        r2.in.sids     = r->in.sids;
        r2.in.names    = NULL;
@@ -641,9 +694,8 @@ NTSTATUS dcesrv_lsa_LookupSids(struct dcesrv_call_state *dce_call, TALLOC_CTX *m
        r2.out.names   = NULL;
 
        status = dcesrv_lsa_LookupSids2(dce_call, mem_ctx, &r2);
-       if (dce_call->fault_code != 0) {
-               return status;
-       }
+       /* we deliberately don't check for error from the above,
+          as even on error we are supposed to return the names  */
 
        r->out.domains = r2.out.domains;
        if (!r2.out.names) {
@@ -685,6 +737,11 @@ NTSTATUS dcesrv_lsa_LookupNames3(struct dcesrv_call_state *dce_call,
 
        DCESRV_PULL_HANDLE(policy_handle, r->in.handle, LSA_HANDLE_POLICY);
 
+       if (r->in.level < LSA_LOOKUP_NAMES_ALL ||
+           r->in.level > LSA_LOOKUP_NAMES_RODC_REFERRAL_TO_FULL_DC) {
+               return NT_STATUS_INVALID_PARAMETER;
+       }
+
        policy_state = policy_handle->data;
 
        r->out.domains = NULL;
@@ -720,7 +777,7 @@ NTSTATUS dcesrv_lsa_LookupNames3(struct dcesrv_call_state *dce_call,
                r->out.sids->sids[i].sid_type    = SID_NAME_UNKNOWN;
                r->out.sids->sids[i].sid         = NULL;
                r->out.sids->sids[i].sid_index   = 0xFFFFFFFF;
-               r->out.sids->sids[i].unknown     = 0;
+               r->out.sids->sids[i].flags       = 0;
 
                status2 = dcesrv_lsa_lookup_name(dce_call->event_ctx, lp_ctx, policy_state, mem_ctx, name, &authority_name, &sid, &rtype);
                if (!NT_STATUS_IS_OK(status2) || sid->num_auths == 0) {
@@ -730,13 +787,13 @@ NTSTATUS dcesrv_lsa_LookupNames3(struct dcesrv_call_state *dce_call,
                status2 = dcesrv_lsa_authority_list(policy_state, mem_ctx, rtype, authority_name, 
                                                    sid, r->out.domains, &sid_index);
                if (!NT_STATUS_IS_OK(status2)) {
-                       return status2;
+                       continue;
                }
 
                r->out.sids->sids[i].sid_type    = rtype;
                r->out.sids->sids[i].sid         = sid;
                r->out.sids->sids[i].sid_index   = sid_index;
-               r->out.sids->sids[i].unknown     = 0;
+               r->out.sids->sids[i].flags       = 0;
 
                (*r->out.count)++;
        }
@@ -765,6 +822,8 @@ NTSTATUS dcesrv_lsa_LookupNames4(struct dcesrv_call_state *dce_call, TALLOC_CTX
        NTSTATUS status;
        struct dcesrv_handle *h;
 
+       ZERO_STRUCT(r2);
+
        /* No policy handle on the wire, so make one up here */
        r2.in.handle = talloc(mem_ctx, struct policy_handle);
        if (!r2.in.handle) {
@@ -786,18 +845,16 @@ NTSTATUS dcesrv_lsa_LookupNames4(struct dcesrv_call_state *dce_call, TALLOC_CTX
 
        r2.in.num_names = r->in.num_names;
        r2.in.names = r->in.names;
+       r2.in.level = r->in.level;
        r2.in.sids = r->in.sids;
        r2.in.count = r->in.count;
-       r2.in.unknown1 = r->in.unknown1;
-       r2.in.unknown2 = r->in.unknown2;
+       r2.in.lookup_options = r->in.lookup_options;
+       r2.in.client_revision = r->in.client_revision;
        r2.out.domains = r->out.domains;
        r2.out.sids = r->out.sids;
        r2.out.count = r->out.count;
        
        status = dcesrv_lsa_LookupNames3(dce_call, mem_ctx, &r2);
-       if (dce_call->fault_code != 0) {
-               return status;
-       }
        
        r->out.domains = r2.out.domains;
        r->out.sids = r2.out.sids;
@@ -821,6 +878,11 @@ NTSTATUS dcesrv_lsa_LookupNames2(struct dcesrv_call_state *dce_call,
 
        DCESRV_PULL_HANDLE(h, r->in.handle, LSA_HANDLE_POLICY);
 
+       if (r->in.level < LSA_LOOKUP_NAMES_ALL ||
+           r->in.level > LSA_LOOKUP_NAMES_RODC_REFERRAL_TO_FULL_DC) {
+               return NT_STATUS_INVALID_PARAMETER;
+       }
+
        state = h->data;
 
        r->out.domains = talloc_zero(mem_ctx,  struct lsa_RefDomainList);
@@ -851,7 +913,10 @@ NTSTATUS dcesrv_lsa_LookupNames2(struct dcesrv_call_state *dce_call,
                r->out.sids->count++;
 
                r->out.sids->sids[i].sid_type    = SID_NAME_UNKNOWN;
-               r->out.sids->sids[i].rid         = 0xFFFFFFFF;
+               /* MS-LSAT 3.1.4.7 - rid zero is considered equivalent
+                  to sid NULL - so we should return 0 rid for
+                  unmapped entries */
+               r->out.sids->sids[i].rid         = 0;
                r->out.sids->sids[i].sid_index   = 0xFFFFFFFF;
                r->out.sids->sids[i].unknown     = 0;
 
@@ -864,7 +929,7 @@ NTSTATUS dcesrv_lsa_LookupNames2(struct dcesrv_call_state *dce_call,
                status2 = dcesrv_lsa_authority_list(state, mem_ctx, rtype, authority_name, 
                                                    sid, r->out.domains, &sid_index);
                if (!NT_STATUS_IS_OK(status2)) {
-                       return status2;
+                       continue;
                }
 
                r->out.sids->sids[i].sid_type    = rtype;
@@ -895,18 +960,20 @@ NTSTATUS dcesrv_lsa_LookupNames(struct dcesrv_call_state *dce_call, TALLOC_CTX *
        NTSTATUS status;
        int i;
 
+       ZERO_STRUCT(r2);
+
        r2.in.handle    = r->in.handle;
        r2.in.num_names = r->in.num_names;
        r2.in.names     = r->in.names;
        r2.in.sids      = NULL;
        r2.in.level     = r->in.level;
        r2.in.count     = r->in.count;
-       r2.in.unknown1  = 0;
-       r2.in.unknown2  = 0;
+       r2.in.lookup_options = 0;
+       r2.in.client_revision = 0;
        r2.out.count    = r->out.count;
 
        status = dcesrv_lsa_LookupNames2(dce_call, mem_ctx, &r2);
-       if (dce_call->fault_code != 0) {
+       if (r2.out.sids == NULL) {
                return status;
        }
 
index cceb2a62acd880ed677ccf1b631c02572065a934..b948d1210e88483d84be5113900681dde1f3fe0e 100644 (file)
@@ -36,6 +36,7 @@
 #include "param/param.h"
 #include "lib/messaging/irpc.h"
 #include "librpc/gen_ndr/ndr_irpc.h"
+#include "librpc/gen_ndr/ndr_netlogon.h"
 
 struct server_pipe_state {
        struct netr_Credential client_challenge;
@@ -86,6 +87,9 @@ static NTSTATUS dcesrv_netr_ServerAuthenticate3(struct dcesrv_call_state *dce_ca
        const char *attrs[] = {"unicodePwd", "userAccountControl", 
                               "objectSid", NULL};
 
+       const char *trust_dom_attrs[] = {"flatname", NULL};
+       const char *account_name;
+
        ZERO_STRUCTP(r->out.credentials);
        *r->out.rid = 0;
        *r->out.negotiate_flags = *r->in.negotiate_flags;
@@ -100,10 +104,54 @@ static NTSTATUS dcesrv_netr_ServerAuthenticate3(struct dcesrv_call_state *dce_ca
        if (sam_ctx == NULL) {
                return NT_STATUS_INVALID_SYSTEM_SERVICE;
        }
+
+       if (r->in.secure_channel_type == SEC_CHAN_DNS_DOMAIN) {
+               char *encoded_account = ldb_binary_encode_string(mem_ctx, r->in.account_name);
+               char *flatname;
+               if (!encoded_account) {
+                       return NT_STATUS_NO_MEMORY;
+               }
+
+               /* Kill the trailing dot */
+               if (encoded_account[strlen(encoded_account)-1] == '.') {
+                       encoded_account[strlen(encoded_account)-1] = '\0';
+               }
+
+               /* pull the user attributes */
+               num_records = gendb_search(sam_ctx, mem_ctx, NULL, &msgs, trust_dom_attrs,
+                                          "(&(trustPartner=%s)(objectclass=trustedDomain))", 
+                                          encoded_account);
+               
+               if (num_records == 0) {
+                       DEBUG(3,("Couldn't find trust [%s] in samdb.\n", 
+                                encoded_account));
+                       return NT_STATUS_ACCESS_DENIED;
+               }
+               
+               if (num_records > 1) {
+                       DEBUG(0,("Found %d records matching user [%s]\n", num_records, r->in.account_name));
+                       return NT_STATUS_INTERNAL_DB_CORRUPTION;
+               }
+               
+               flatname = ldb_msg_find_attr_as_string(msgs[0], "flatname", NULL);
+               if (!flatname) {
+                       /* No flatname for this trust - we can't proceed */
+                       return NT_STATUS_ACCESS_DENIED;
+               }
+               account_name = talloc_asprintf(mem_ctx, "%s$", flatname);
+
+               if (!account_name) {
+                       return NT_STATUS_NO_MEMORY;
+               }
+               
+       } else {
+               account_name = r->in.account_name;
+       }
+       
        /* pull the user attributes */
        num_records = gendb_search(sam_ctx, mem_ctx, NULL, &msgs, attrs,
                                   "(&(sAMAccountName=%s)(objectclass=user))", 
-                                  r->in.account_name);
+                                  ldb_binary_encode_string(mem_ctx, account_name));
 
        if (num_records == 0) {
                DEBUG(3,("Couldn't find user [%s] in samdb.\n", 
@@ -129,7 +177,8 @@ static NTSTATUS dcesrv_netr_ServerAuthenticate3(struct dcesrv_call_state *dce_ca
                        DEBUG(1, ("Client asked for a workstation secure channel, but is not a workstation (member server) acb flags: 0x%x\n", user_account_control));
                        return NT_STATUS_ACCESS_DENIED;
                }
-       } else if (r->in.secure_channel_type == SEC_CHAN_DOMAIN) {
+       } else if (r->in.secure_channel_type == SEC_CHAN_DOMAIN || 
+                  r->in.secure_channel_type == SEC_CHAN_DNS_DOMAIN) {
                if (!(user_account_control & UF_INTERDOMAIN_TRUST_ACCOUNT)) {
                        DEBUG(1, ("Client asked for a trusted domain secure channel, but is not a trusted domain: acb flags: 0x%x\n", user_account_control));
                        
@@ -898,20 +947,37 @@ static NTSTATUS fill_domain_trust_info(TALLOC_CTX *mem_ctx,
                                       struct ldb_message *res,
                                       struct ldb_message *ref_res,
                                       struct netr_DomainTrustInfo *info, 
-                                      bool is_local)
+                                      bool is_local, bool is_trust_list)
 {
        ZERO_STRUCTP(info);
 
+       info->trust_extension.info = talloc_zero(mem_ctx, struct netr_trust_extension);
+       info->trust_extension.length = 16;
+       info->trust_extension.info->flags = 
+               NETR_TRUST_FLAG_TREEROOT | 
+               NETR_TRUST_FLAG_IN_FOREST | 
+               NETR_TRUST_FLAG_PRIMARY;
+       info->trust_extension.info->parent_index = 0; /* should be index into array
+                                                        of parent */
+       info->trust_extension.info->trust_type = LSA_TRUST_TYPE_UPLEVEL; /* should be based on ldb search for trusts */
+       info->trust_extension.info->trust_attributes = LSA_TRUST_ATTRIBUTE_NON_TRANSITIVE; /* needs to be based on ldb search */
+
+       if (is_trust_list) {
+               /* MS-NRPC 3.5.4.3.9 - must be set to NULL for trust list */
+               info->forest.string = NULL;
+       } else {
+               /* TODO: we need a common function for pulling the forest */
+               info->forest.string = samdb_result_string(ref_res, "dnsRoot", NULL);
+       }
+
        if (is_local) {
                info->domainname.string = samdb_result_string(ref_res, "nETBIOSName", NULL);
                info->fulldomainname.string = samdb_result_string(ref_res, "dnsRoot", NULL);
-               info->forest.string = NULL;
                info->guid = samdb_result_guid(res, "objectGUID");
                info->sid = samdb_result_dom_sid(mem_ctx, res, "objectSid");
        } else {
                info->domainname.string = samdb_result_string(res, "flatName", NULL);
                info->fulldomainname.string = samdb_result_string(res, "trustPartner", NULL);
-               info->forest.string = NULL;
                info->guid = samdb_result_guid(res, "objectGUID");
                info->sid = samdb_result_dom_sid(mem_ctx, res, "securityIdentifier");
        }
@@ -947,6 +1013,9 @@ static NTSTATUS dcesrv_netr_LogonGetDomainInfo(struct dcesrv_call_state *dce_cal
                                              r->in.credential, 
                                              r->out.return_authenticator,
                                              NULL);
+       if (!NT_STATUS_IS_OK(status)) {
+               DEBUG(0,(__location__ " Bad credentials - error\n"));
+       }
        NT_STATUS_NOT_OK_RETURN(status);
 
        sam_ctx = samdb_connect(mem_ctx, dce_call->event_ctx, dce_call->conn->dce_ctx->lp_ctx, dce_call->conn->auth_state.session_info);
@@ -992,17 +1061,25 @@ static NTSTATUS dcesrv_netr_LogonGetDomainInfo(struct dcesrv_call_state *dce_cal
                                       info1->num_trusts);
        NT_STATUS_HAVE_NO_MEMORY(info1->trusts);
 
-       status = fill_domain_trust_info(mem_ctx, res1[0], ref_res[0], &info1->domaininfo, true);
+       status = fill_domain_trust_info(mem_ctx, res1[0], ref_res[0], &info1->domaininfo, 
+                                       true, false);
        NT_STATUS_NOT_OK_RETURN(status);
 
        for (i=0;i<ret2;i++) {
-               status = fill_domain_trust_info(mem_ctx, res2[i], NULL, &info1->trusts[i], false);
+               status = fill_domain_trust_info(mem_ctx, res2[i], NULL, &info1->trusts[i], 
+                                               false, true);
                NT_STATUS_NOT_OK_RETURN(status);
        }
 
-       status = fill_domain_trust_info(mem_ctx, res1[0], ref_res[0], &info1->trusts[i], true);
+       status = fill_domain_trust_info(mem_ctx, res1[0], ref_res[0], &info1->trusts[i], 
+                                       true, true);
        NT_STATUS_NOT_OK_RETURN(status);
 
+       info1->dns_hostname.string = samdb_result_string(ref_res[0], "dnsRoot", NULL);
+       info1->workstation_flags = 
+               NETR_WS_FLAG_HANDLES_INBOUND_TRUSTS | NETR_WS_FLAG_HANDLES_SPN_UPDATE;
+       info1->supported_enc_types = 0; /* w2008 gives this 0 */
+
        r->out.info.info1 = info1;
 
        return NT_STATUS_OK;
index b68cec4c7dba190167099a55e498e66319e75eaa..2ef8591c320a97144d7a737a7e040479f9125a28 100644 (file)
@@ -436,6 +436,25 @@ static void dcesrv_task_init(struct task_server *task)
        NTSTATUS status;
        struct dcesrv_context *dce_ctx;
        struct dcesrv_endpoint *e;
+       extern NTSTATUS dcerpc_server_wkssvc_init(void);
+       extern NTSTATUS dcerpc_server_drsuapi_init(void);
+       extern NTSTATUS dcerpc_server_winreg_init(void);
+       extern NTSTATUS dcerpc_server_spoolss_init(void);
+       extern NTSTATUS dcerpc_server_epmapper_init(void);
+       extern NTSTATUS dcerpc_server_srvsvc_init(void);
+       extern NTSTATUS dcerpc_server_netlogon_init(void);
+       extern NTSTATUS dcerpc_server_rpcecho_init(void);
+       extern NTSTATUS dcerpc_server_unixinfo_init(void);
+       extern NTSTATUS dcerpc_server_samr_init(void);
+       extern NTSTATUS dcerpc_server_remote_init(void);
+       extern NTSTATUS dcerpc_server_lsa_init(void);
+       init_module_fn static_init[] = { STATIC_DCESRV_MODULES };
+       init_module_fn *shared_init = load_samba_modules(NULL, task->lp_ctx, "dcerpc_server");
+
+       run_init_functions(static_init);
+       run_init_functions(shared_init);
+
+       talloc_free(shared_init);
 
        task_server_set_title(task, "task[dcesrv]");
 
@@ -462,25 +481,6 @@ failed:
 
 NTSTATUS server_service_rpc_init(void)
 {
-       extern NTSTATUS dcerpc_server_wkssvc_init(void);
-       extern NTSTATUS dcerpc_server_drsuapi_init(void);
-       extern NTSTATUS dcerpc_server_winreg_init(void);
-       extern NTSTATUS dcerpc_server_spoolss_init(void);
-       extern NTSTATUS dcerpc_server_epmapper_init(void);
-       extern NTSTATUS dcerpc_server_srvsvc_init(void);
-       extern NTSTATUS dcerpc_server_netlogon_init(void);
-       extern NTSTATUS dcerpc_server_rpcecho_init(void);
-       extern NTSTATUS dcerpc_server_unixinfo_init(void);
-       extern NTSTATUS dcerpc_server_samr_init(void);
-       extern NTSTATUS dcerpc_server_remote_init(void);
-       extern NTSTATUS dcerpc_server_lsa_init(void);
-       init_module_fn static_init[] = { STATIC_DCESRV_MODULES };
-       init_module_fn *shared_init = load_samba_modules(NULL, global_loadparm, "dcerpc_server");
 
-       run_init_functions(static_init);
-       run_init_functions(shared_init);
-
-       talloc_free(shared_init);
-       
        return register_server_service("rpc", dcesrv_task_init);
 }
index 5fa40ee70664704f6819d8ac882513734cb70ea9..e3e2d2d52524aea660f326cdeb5032f8d2687a66 100644 (file)
@@ -59,4 +59,3 @@ samba4.ntvfs.cifs.raw.
 ^samba4.net.api.become.dc.*$                   # Fails
 nss.test                                               # Fails
 raw.offline                    # Samba 4 doesn't have much offline support yet
-winreg*  #Does not authenticate against the target server
index 962c9562b1b962b9490cdea74d18d7550c0e3535..cc9ff0b9eae2f39878193403be9d6fe5d50d15c7 100755 (executable)
@@ -15,7 +15,9 @@ for p in $*; do
    mv $LIBDIR/$p2 $LIBDIR/$p2.old
  fi
  cp $p $LIBDIR/
- ln -sf $p2 $LIBDIR/$lnname
+ if [ $p2 != $lnname ]; then
+  ln -sf $p2 $LIBDIR/$lnname
+ fi
 done
 
 cat << EOF
index eb347307ba05db731a1474533eff44031c9757c6..2bd34b119f34483929616da1f68be2cfe2f1723a 100755 (executable)
@@ -3,7 +3,6 @@
 
 SRCDIR="$1"
 SETUPDIR="$2"
-BINDIR="$3"
 
 cd $SRCDIR || exit 1
 
@@ -25,9 +24,4 @@ cp setup/provision.smb.conf.dc $SETUPDIR || exit 1
 cp setup/provision.smb.conf.member $SETUPDIR || exit 1
 cp setup/provision.smb.conf.standalone $SETUPDIR || exit 1
 
-echo "Installing script tools"
-mkdir -p "$BINDIR"
-rm -f scripting/bin/*~
-cp scripting/bin/* $BINDIR/ || exit 1
-
 exit 0
diff --git a/source4/script/uninstallheader.sh b/source4/script/uninstallheader.sh
deleted file mode 100755 (executable)
index cb491f0..0000000
+++ /dev/null
@@ -1,35 +0,0 @@
-#!/bin/sh
-# based on uninstallbin.sh:
-#  4 July 96 Dan.Shearer@UniSA.edu.au   
-
-INCLUDEDIR=$1
-shift
-
-if [ ! -d $INCLUDEDIR ]; then
-  echo Directory $INCLUDEDIR does not exist!
-  echo Do a "make installbin" or "make install" first.
-  exit 1
-fi
-
-for p in $*; do
-  p2=`basename $p`
-  if [ -f $INCLUDEDIR/$p2 ]; then
-    echo Removing $INCLUDEDIR/$p2
-    rm -f $INCLUDEDIR/$p2
-    if [ -f $INCLUDEDIR/$p2 ]; then
-      echo Cannot remove $INCLUDEDIR/$p2 ... does $USER have privileges?
-    fi
-  fi
-done
-
-
-cat << EOF
-======================================================================
-The headers have been uninstalled. You may restore the headers using
-the command "make installheader" or "make install" to install binaries, 
-man pages, modules and shell scripts. You can restore a previous
-version of the headers (if there were any) using "make revert".
-======================================================================
-EOF
-
-exit 0
index 111557126d4032d18ab2cee255e146a9eaf4b640..e7d7ed497913e752ac267e482d4f0e0506fbef3d 100755 (executable)
@@ -11,7 +11,8 @@ import os, sys
 sys.path.insert(0, "bin/python")
 
 import samba
-from samba import getopt as options
+from samba import getopt as options, Ldb
+from ldb import SCOPE_SUBTREE, SCOPE_BASE, LdbError
 import sys
 
 parser = optparse.OptionParser("minschema <URL> <classfile>")
@@ -50,7 +51,9 @@ if len(args) != 2:
 
 (url, classfile) = args
 
-creds = credopts.get_credentials()
+lp_ctx = sambaopts.get_loadparm()
+
+creds = credopts.get_credentials(lp_ctx)
 ldb = Ldb(url, credentials=creds)
 
 objectclasses = []
@@ -131,17 +134,10 @@ attrib_attrs = ["objectClass",
 #      2: abstract
 #      3: auxiliary
 
-#
-#  print only if verbose is set
-#
-def dprintf(text):
-    if verbose is not None:
-        print text
-
 def get_object_cn(ldb, name):
     attrs = ["cn"]
 
-    res = ldb.search("(ldapDisplayName=%s)" % name, rootDse["schemaNamingContext"], ldb.SCOPE_SUBTREE, attrs)
+    res = ldb.search("(ldapDisplayName=%s)" % name, rootDse["schemaNamingContext"], SCOPE_SUBTREE, attrs)
     assert len(res) == 1
 
     return res[0]["cn"]
@@ -229,7 +225,7 @@ def find_objectclass_properties(ldb, o):
     """the properties of an objectclass"""
     res = ldb.search(
         expression="(ldapDisplayName=%s)" % o.name,
-        basedn=rootDse["schemaNamingContext"], scope=ldb.SCOPE_SUBTREE, attrs=class_attrs)
+        base=rootDse["schemaNamingContext"], scope=SCOPE_SUBTREE, attrs=class_attrs)
     assert(len(res) == 1)
     msg = res[0]
     for a in msg:
@@ -239,7 +235,7 @@ def find_attribute_properties(ldb, o):
     """find the properties of an attribute"""
     res = ldb.search(
         expression="(ldapDisplayName=%s)" % o.name,
-        basedn=rootDse["schemaNamingContext"], scope=ldb.SCOPE_SUBTREE, 
+        base=rootDse["schemaNamingContext"], scope=SCOPE_SUBTREE, 
         attrs=attrib_attrs)
     assert(len(res) == 1)
     msg = res[0]
@@ -269,7 +265,7 @@ def find_objectclass_auto(ldb, o):
         print "%s\n" % ldif
         return
 
-    res = ldb.search("", testdn, ldb.SCOPE_BASE)
+    res = ldb.search(base=testdn, scope=ldb.SCOPE_BASE)
     ldb.delete(testdn)
 
     for a in res.msgs[0]:
@@ -284,7 +280,7 @@ def expand_objectclass(ldb, o):
                   "subClassOf"]
     res = ldb.search(
         expression="(&(objectClass=classSchema)(ldapDisplayName=%s))" % o.name,
-        basedn=rootDse["schemaNamingContext"], scope=ldb.SCOPE_SUBTREE, 
+        base=rootDse["schemaNamingContext"], scope=SCOPE_SUBTREE, 
         attrs=attrs)
     print "Expanding class %s\n" % o.name
     assert(len(res) == 1)
@@ -322,13 +318,13 @@ def walk_dn(ldb, dn):
     # get a list of all possible attributes for this object 
     attrs = ["allowedAttributes"]
     try:
-        res = ldb.search("objectClass=*", dn, ldb.SCOPE_BASE, attrs)
+        res = ldb.search("objectClass=*", dn, SCOPE_BASE, attrs)
     except LdbError, e:
         print "Unable to fetch allowedAttributes for '%s' - %r\n" % (dn, e)
         return
     allattrs = res[0]["allowedAttributes"]
     try:
-        res = ldb.search("objectClass=*", dn, ldb.SCOPE_BASE, allattrs)
+        res = ldb.search("objectClass=*", dn, SCOPE_BASE, allattrs)
     except LdbError, e:
         print "Unable to fetch all attributes for '%s' - %s\n" % (dn, e)
         return
@@ -340,7 +336,7 @@ def walk_dn(ldb, dn):
 def walk_naming_context(ldb, namingContext):
     """walk a naming context, looking for all records"""
     try:
-        res = ldb.search("objectClass=*", namingContext, ldb.SCOPE_DEFAULT, 
+        res = ldb.search("objectClass=*", namingContext, SCOPE_DEFAULT, 
                          ["objectClass"])
     except LdbError, e:
         print "Unable to fetch objectClasses for '%s' - %s\n" % (namingContext, e)
@@ -398,7 +394,7 @@ def build_objectclass(ldb, name):
     try:
         res = ldb.search(
             expression="(&(objectClass=classSchema)(ldapDisplayName=%s))" % name,
-            basedn=rootDse["schemaNamingContext"], scope=ldb.SCOPE_SUBTREE, 
+            base=rootDse["schemaNamingContext"], scope=SCOPE_SUBTREE, 
             attrs=attrs)
     except LdbError, e:
         print "unknown class '%s'\n" % name
@@ -503,10 +499,10 @@ objectCategory: CN=SubSchema,${SCHEMADN}
 
 def load_list(file):
     """load a list from a file"""
-    return open(file, 'r').splitlines()
+    return open(file, 'r').readlines()
 
 # get the rootDSE
-res = ldb.search("", "", ldb.SCOPE_BASE)
+res = ldb.search(base="", expression="", scope=SCOPE_BASE, attrs=["schemaNamingContext"])
 rootDse = res[0]
 
 # load the list of classes we are interested in
index 6f1086ad376c653087cb703a78dd61dd2e351c35..e7737bdbecc354f91e8f0142f13a2af851fd3898 100755 (executable)
@@ -21,6 +21,7 @@ import sys
 
 # Find right directory when running from source tree
 sys.path.insert(0, "bin/python")
+sys.path.insert(1, "../lib/subunit/python")
 
 from subunit import SubunitTestRunner
 from unittest import TestProgram
index b494ee6e8d4fc968eedb287a93558601d56bd36f..c88728a9fdc6ef1df45fe78182da41544dbc63cc 100644 (file)
@@ -23,7 +23,7 @@ python_misc_OBJ_FILES = $(pyscriptsrcdir)/misc_wrap.o
 
 $(python_misc_OBJ_FILES): CFLAGS+=$(CFLAG_NO_UNUSED_MACROS) $(CFLAG_NO_CAST_QUAL)
 
-_PY_FILES = $(shell find $(pyscriptsrcdir)/samba $(pyscriptsrcdir)/subunit -name "*.py")
+_PY_FILES = $(shell find $(pyscriptsrcdir)/samba ../lib/subunit/python -name "*.py")
 
 $(foreach pyfile, $(_PY_FILES),$(eval $(call python_py_module_template,$(patsubst $(pyscriptsrcdir)/%,%,$(pyfile)),$(pyfile))))
 
@@ -32,6 +32,6 @@ $(eval $(call python_py_module_template,samba/misc.py,$(pyscriptsrcdir)/misc.py)
 EPYDOC_OPTIONS = --no-private --url http://www.samba.org/ --no-sourcecode
 
 epydoc:: pythonmods
-       PYTHONPATH=$(pythonbuilddir) epydoc $(EPYDOC_OPTIONS) samba tdb ldb subunit
+       PYTHONPATH=$(pythonbuilddir):../lib/subunit/python epydoc $(EPYDOC_OPTIONS) samba tdb ldb subunit
 
 install:: installpython
index 68f61532ad8d44358ae597f49bc3a8733e674e84..427ca975b357ccb1a1fab05736b5d38ac75a70bc 100644 (file)
@@ -744,6 +744,8 @@ def setup_samdb(path, setup_path, session_info, credentials, lp,
 
     samdb = SamDB(path, session_info=session_info, 
                   credentials=credentials, lp=lp)
+    if fill == FILL_DRS:
+        return samdb
 
     message("Pre-loading the Samba 4 and AD schema")
     samdb.set_domain_sid(domainsid)
index 12638e2397b63ccbdbb3082a6ff3d38a5ef7eaa5..06790736b8d3f2a9cda43c2a363bdd090c03387d 100644 (file)
@@ -25,7 +25,8 @@ from samba.tests import RpcInterfaceTestCase
 
 class RpcEchoTests(RpcInterfaceTestCase):
     def setUp(self):
-        self.conn = echo.rpcecho("ncalrpc:", self.get_loadparm())
+        self.conn = echo.rpcecho("ncalrpc:", self.get_loadparm(),
+                                 self.get_credentials())
 
     def test_two_contexts(self):
         self.conn2 = echo.rpcecho("ncalrpc:", self.get_loadparm(), basis_connection=self.conn)
index 2fcb71eb7ae658b8bdeb664ec5350c9cbd94189a..e4bb2df0ad90c11531cf1d187e27e81082cd9e8e 100644 (file)
@@ -49,6 +49,9 @@ quicktestone:: all
 testenv:: everything
        $(SELFTEST) $(SELFTEST_NOSLOW_OPTS) --socket-wrapper --testenv
 
+testenv-%:: everything
+       SELFTEST_TESTENV=$* $(SELFTEST) $(SELFTEST_NOSLOW_OPTS) --socket-wrapper --testenv
+
 valgrindtest:: valgrindtest-all
 
 valgrindtest-quick:: all
index 36d52fff5a0b4ab8557c33e0619528e71af3d2e2..9fc71a104f4006199d3ed17602aadcf67a1635c3 100755 (executable)
@@ -91,7 +91,7 @@ plantest "ldb" none TEST_DATA_PREFIX=\$PREFIX $LDBDIR/tests/test-tdb.sh
 # that they stay passing
 ncacn_np_tests="RPC-SCHANNEL RPC-JOIN RPC-LSA RPC-DSSETUP RPC-ALTERCONTEXT RPC-MULTIBIND RPC-NETLOGON RPC-HANDLES RPC-SAMSYNC RPC-SAMBA3SESSIONKEY RPC-SAMBA3-GETUSERNAME RPC-SAMBA3-LSA RPC-BINDSAMBA3 RPC-NETLOGSAMBA3 RPC-ASYNCBIND RPC-LSALOOKUP RPC-LSA-GETUSER RPC-SCHANNEL2 RPC-AUTHCONTEXT"
 ncalrpc_tests="RPC-SCHANNEL RPC-JOIN RPC-LSA RPC-DSSETUP RPC-ALTERCONTEXT RPC-MULTIBIND RPC-NETLOGON RPC-DRSUAPI RPC-ASYNCBIND RPC-LSALOOKUP RPC-LSA-GETUSER RPC-SCHANNEL2 RPC-AUTHCONTEXT"
-ncacn_ip_tcp_tests="RPC-SCHANNEL RPC-JOIN RPC-LSA RPC-DSSETUP RPC-ALTERCONTEXT RPC-MULTIBIND RPC-NETLOGON RPC-HANDLES RPC-DSSYNC RPC-ASYNCBIND RPC-LSALOOKUP RPC-LSA-GETUSER RPC-SCHANNEL2 RPC-AUTHCONTEXT"
+ncacn_ip_tcp_tests="RPC-SCHANNEL RPC-JOIN RPC-LSA RPC-DSSETUP RPC-ALTERCONTEXT RPC-MULTIBIND RPC-NETLOGON RPC-HANDLES RPC-DSSYNC RPC-ASYNCBIND RPC-LSALOOKUP RPC-LSA-GETUSER RPC-SCHANNEL2 RPC-AUTHCONTEXT RPC-OBJECTUUID"
 slow_ncacn_np_tests="RPC-SAMLOGON RPC-SAMR RPC-SAMR-USERS RPC-SAMR-PASSWORDS"
 slow_ncalrpc_tests="RPC-SAMR RPC-SAMR-PASSWORDS"
 slow_ncacn_ip_tcp_tests="RPC-SAMR RPC-SAMR-PASSWORDS RPC-CRACKNAMES"
@@ -252,7 +252,7 @@ if test x"${PIDL_TESTS_SKIP}" = x"yes"; then
    echo "Skipping pidl tests - PIDL_TESTS_SKIP=yes"
 elif $PERL -e 'eval require Test::More;' > /dev/null 2>&1; then
   for f in $samba4srcdir/../pidl/tests/*.pl; do
-     plantest "pidl.`basename $f .pl`" none $PERL $f "|" $samba4srcdir/script/harness2subunit.pl
+     plantest "pidl.`basename $f .pl`" none $PERL $f "|" $samba4srcdir/../lib/subunit/harness2subunit.pl
   done
 else 
    echo "Skipping pidl tests - Test::More not installed"
@@ -326,11 +326,11 @@ for mech in \
        "-k no --option=gensec:spengo=no"; do
        signoptions="$mech --signing=off"
        name="smb.signing on with $signoptions"
-       plantest "$name local-creds" member $VALGRIND $smb4torture //"\$NETBIOSNAME"/tmp $signoptions -U"\$NETBIOSNAME\\\\\$USERNAME"%"\$PASSWORD" BASE-XCOPY "$*"
+       plantest "$name local-creds" member $VALGRIND $smb4torture //"\$NETBIOSNAME"/tmp $signoptions -U"\$NETBIOSNAME/\$USERNAME"%"\$PASSWORD" BASE-XCOPY "$*"
 done
-plantest "--signing=yes anon" dc $VALGRIND $smb4torture //"\$NETBIOSNAME"/tmp -k no --signing=yes -U% BASE-XCOPY "$*"
-plantest "--signing=required anon" dc $VALGRIND $smb4torture //"\$NETBIOSNAME"/tmp -k no --signing=required -U% BASE-XCOPY "$*"
-plantest "--signing=no anon" member $VALGRIND $smb4torture //"\$NETBIOSNAME"/tmp -k no --signing=no -U% BASE-XCOPY "$*"
+plantest "smb.signing --signing=yes anon" dc $VALGRIND $smb4torture //"\$NETBIOSNAME"/tmp -k no --signing=yes -U% BASE-XCOPY "$*"
+plantest "smb.signing --signing=required anon" dc $VALGRIND $smb4torture //"\$NETBIOSNAME"/tmp -k no --signing=required -U% BASE-XCOPY "$*"
+plantest "smb.signing --signing=no anon" member $VALGRIND $smb4torture //"\$NETBIOSNAME"/tmp -k no --signing=no -U% BASE-XCOPY "$*"
 
 NBT_TESTS=`$smb4torture --list | grep "^NBT-" | xargs`
 
@@ -381,6 +381,7 @@ plantest "samdb.python" none $SUBUNITRUN samba.tests.samdb
 plantest "events.python" none PYTHONPATH="$PYTHONPATH:lib/events" $SUBUNITRUN tests
 plantest "messaging.python" none PYTHONPATH="$PYTHONPATH:lib/messaging/tests" $SUBUNITRUN bindings
 plantest "samba3sam.python" none PYTHONPATH="$PYTHONPATH:dsdb/samdb/ldb_modules/tests" $SUBUNITRUN samba3sam
+plantest "subunit.python" none $SUBUNITRUN subunit
 plantest "rpcecho.python" dc $SUBUNITRUN samba.tests.dcerpc.rpcecho
 plantest "winreg.python" dc $SUBUNITRUN -U\$USERNAME%\$PASSWORD samba.tests.dcerpc.registry
 plantest "ldap.python" dc $PYTHON $samba4srcdir/lib/ldb/tests/python/ldap.py $CONFIGURATION \$SERVER -U\$USERNAME%\$PASSWORD -W \$DOMAIN
index 63332e937b2a72b3930c53506014951047c686fa..a7b501e8a8741b4ed20e1b4dd760a0f8590c1fd5 100644 (file)
@@ -77,4 +77,12 @@ subRefs: ${SCHEMADN}
 replace: gPLink
 gPLink: [LDAP://CN={${POLICYGUID}},CN=Policies,CN=System,${DOMAINDN};0]
 -
+replace: wellKnownObjects
+wellKnownObjects: B:32:22b70c67d56e4efb91e9300fca3dc1aa:CN=ForeignSecurityPrincipals,${DOMAINDN}
+wellKnownObjects: B:32:2fbac1870ade11d297c400c04fd8d5cd:CN=Infrastructure,${DOMAINDN}
+wellKnownObjects: B:32:ab1d30f3768811d1aded00c04fd8d5cd:CN=System,${DOMAINDN}
+wellKnownObjects: B:32:a361b2ffffd211d1aa4b00c04fd7d83a:OU=Domain Controllers,${DOMAINDN}
+wellKnownObjects: B:32:aa312825768811d1aded00c04fd8d5cd:CN=Computers,${DOMAINDN}
+wellKnownObjects: B:32:a9d1ca15768811d1aded00c04fd8d5cd:CN=Users,${DOMAINDN}
+-
 ${DOMAINGUID_MOD}
index 854c42d07c4f037bd583a92b406f065fb9bb528d..c61cb805c49c607653d4b448fe41031964c71235 100644 (file)
@@ -137,6 +137,66 @@ sAMAccountName: RAS and IAS Servers
 groupType: -2147483644
 isCriticalSystemObject: TRUE
 
+dn: CN=Read-Only Domain Controllers,CN=Users,${DOMAINDN}
+objectClass: top
+objectClass: group
+cn: Read-Only Domain Controllers
+description: read-only domain controllers
+objectSid: ${DOMAINSID}-521
+sAMAccountName: Read-Only Domain Controllers
+groupType: -2147483644
+isCriticalSystemObject: TRUE
+
+dn: CN=Enterprise Read-Only Domain Controllers,CN=Users,${DOMAINDN}
+objectClass: top
+objectClass: group
+cn: Enterprise Read-Only Domain Controllers
+description: enterprise read-only domain controllers
+objectSid: ${DOMAINSID}-498
+sAMAccountName: Enterprise Read-Only Domain Controllers
+groupType: -2147483644
+isCriticalSystemObject: TRUE
+
+dn: CN=Certificate Service DCOM Access,CN=Users,${DOMAINDN}
+objectClass: top
+objectClass: group
+cn: Certificate Service DCOM Access
+description: Certificate Service DCOM Access
+objectSid: ${DOMAINSID}-574
+sAMAccountName: Certificate Service DCOM Access
+groupType: -2147483644
+isCriticalSystemObject: TRUE
+
+dn: CN=Cryptographic Operators,CN=Users,${DOMAINDN}
+objectClass: top
+objectClass: group
+cn: Cryptographic Operators
+description: Cryptographic Operators
+objectSid: ${DOMAINSID}-569
+sAMAccountName: Cryptographic Operators
+groupType: -2147483644
+isCriticalSystemObject: TRUE
+
+dn: CN=Event Log Readers,CN=Users,${DOMAINDN}
+objectClass: top
+objectClass: group
+cn: Event Log Readers
+description: Event Log Readers
+objectSid: ${DOMAINSID}-573
+sAMAccountName: Event Log Readers
+groupType: -2147483644
+isCriticalSystemObject: TRUE
+
+dn: CN=IIS_IUSRS,CN=Users,${DOMAINDN}
+objectClass: top
+objectClass: group
+cn: IIS_IUSRS
+description: IIS_IUSRS
+objectSid: ${DOMAINSID}-568
+sAMAccountName: IIS_IUSRS
+groupType: -2147483644
+isCriticalSystemObject: TRUE
+
 dn: CN=Administrators,CN=Builtin,${DOMAINDN}
 objectClass: top
 objectClass: group
index 3e129e4f6b09c8465f5e377409d969c760ce6079..2c007395fb4f00e2f0b0219870b31d98af9a6640 100644 (file)
@@ -174,6 +174,8 @@ oMSyntax: 20
 
 #Allocated: DSDB_CONTROL_CURRENT_PARTITION_OID 1.3.6.1.4.1.7165.4.3.2
 
+#Allocated: DSDB_CONTROL_REPLICATED_UPDATE_OID 1.3.6.1.4.1.7165.4.3.3
+
 #Allocated: DSDB_EXTENDED_REPLICATED_OBJECTS_OID 1.3.6.1.4.1.7165.4.4.1
 
 #Allocated: (middleName) attributeID: 1.3.6.1.4.1.7165.4.255.1
index abc5860cf7cae767889c2cb16d60130065dafaa4..8ae5578e6b4f6820762d4435e3148ebb9e4b6263 100644 (file)
@@ -22,7 +22,7 @@ realm: ${REALM}
 sAMAccountName: krbtgt
 objectSid: ${DOMAINSID}
 servicePrincipalName: kadmin/changepw
-krb5Keytab: HDB:ldb:${SAM_LDB}:
+krb5Keytab: HDB:samba4:${SAM_LDB}:
 #The trailing : here is a HACK, but it matches the Heimdal format. 
 
 # A hook from our credentials system into HDB, as we must be on a KDC,
index 368b81d18e5cf9d29929aa04161c9e3d2d05f934..4f018a51439612f257e506caef9d9d15deddef4b 100644 (file)
@@ -35,7 +35,7 @@
 
 #define BLOB_CHECK_MIN_SIZE(blob, size) do { \
        if ((blob)->length < (size)) { \
-               return NT_STATUS_INFO_LENGTH_MISMATCH; \
+               return NT_STATUS_INVALID_PARAMETER; \
        } \
 } while (0)
 
@@ -530,13 +530,14 @@ NTSTATUS smbsrv_pull_passthru_sfileinfo(TALLOC_CTX *mem_ctx,
 
        switch (level) {
        case SMB_SFILEINFO_BASIC_INFORMATION:
-               BLOB_CHECK_MIN_SIZE(blob, 36);
+               BLOB_CHECK_MIN_SIZE(blob, 40);
 
                st->basic_info.in.create_time = pull_nttime(blob->data,  0);
                st->basic_info.in.access_time = pull_nttime(blob->data,  8);
                st->basic_info.in.write_time =  pull_nttime(blob->data, 16);
                st->basic_info.in.change_time = pull_nttime(blob->data, 24);
-               st->basic_info.in.attrib =      IVAL(blob->data,        32);
+               st->basic_info.in.attrib      = IVAL(blob->data,        32);
+               st->basic_info.in.reserved    = IVAL(blob->data,        36);
 
                return NT_STATUS_OK;
 
@@ -581,6 +582,27 @@ NTSTATUS smbsrv_pull_passthru_sfileinfo(TALLOC_CTX *mem_ctx,
 
                return NT_STATUS_OK;
 
+
+       case RAW_SFILEINFO_LINK_INFORMATION:
+               if (!bufinfo) {
+                       return NT_STATUS_INTERNAL_ERROR;
+               }
+               BLOB_CHECK_MIN_SIZE(blob, 20);
+               st->link_information.in.overwrite = CVAL(blob->data, 0);
+               st->link_information.in.root_fid  = IVAL(blob->data, 8);
+               len                                 = IVAL(blob->data, 16);
+               ofs                                 = 20;
+               str_blob = *blob;
+               str_blob.length = MIN(str_blob.length, ofs+len);
+               smbsrv_blob_pull_string(bufinfo, &str_blob, ofs,
+                                       &st->link_information.in.new_name,
+                                       STR_UNICODE);
+               if (st->link_information.in.new_name == NULL) {
+                       return NT_STATUS_FOOBAR;
+               }
+
+               return NT_STATUS_OK;
+
        case RAW_SFILEINFO_RENAME_INFORMATION_SMB2:
                /* SMB2 uses a different format for rename information */
                if (!bufinfo) {
index 8ed03b17febeb33bdbe387d970df043784f194de..6a1a50ffbf345cab432b8ec2d0fa441a75c36045 100644 (file)
@@ -13,7 +13,7 @@ $(eval $(call proto_header_template,$(smb_serversrcdir)/service_smb_proto.h,$(SE
 #
 [MODULE::SERVICE_SAMBA3_SMB]
 INIT_FUNCTION = server_service_samba3_smb_init
-SUBSYSTEM = smbd
+SUBSYSTEM = samba
 
 SERVICE_SAMBA3_SMB_OBJ_FILES = $(smb_serversrcdir)/smb_samba3.o
 
index c7fa2d7d8abca1959b121b2c961d5c9bc20b90ef..241c2628572c2fdd1acb9fa8ab41bac92fc302b2 100644 (file)
@@ -135,7 +135,12 @@ void smbsrv_setup_reply(struct smbsrv_request *req, uint_t wct, size_t buflen)
        flags2 = FLAGS2_LONG_PATH_COMPONENTS | 
                FLAGS2_EXTENDED_ATTRIBUTES | 
                FLAGS2_IS_LONG_NAME;
-       flags2 |= (req->flags2 & (FLAGS2_UNICODE_STRINGS|FLAGS2_EXTENDED_SECURITY));
+#define _SMB_FLAGS2_ECHOED_FLAGS ( \
+       FLAGS2_UNICODE_STRINGS | \
+       FLAGS2_EXTENDED_SECURITY | \
+       FLAGS2_SMB_SECURITY_SIGNATURES \
+)
+       flags2 |= (req->flags2 & _SMB_FLAGS2_ECHOED_FLAGS);
        if (req->smb_conn->negotiate.client_caps & CAP_STATUS32) {
                flags2 |= FLAGS2_32_BIT_ERROR_CODES;
        }
index 6c4b8f33d5b839ce604880fcc69b9199104136c7..82b006c4a1bd0f1a88523a431f5ebfc039fad8e0 100644 (file)
@@ -369,7 +369,7 @@ void smb2srv_setinfo_recv(struct smb2srv_request *req)
        SMB2SRV_SETUP_NTVFS_REQUEST(smb2srv_setinfo_send, NTVFS_ASYNC_STATE_MAY_ASYNC);
 
        info->in.level                  = SVAL(req->in.body, 0x02);
-       SMB2SRV_CHECK(smb2_pull_s32o32_blob(&req->in, info, req->in.body+0x04, &info->in.blob));
+       SMB2SRV_CHECK(smb2_pull_s32o16_blob(&req->in, info, req->in.body+0x04, &info->in.blob));
        info->in.flags                  = IVAL(req->in.body, 0x0C);
        info->in.file.ntvfs             = smb2srv_pull_handle(req, req->in.body, 0x10);
 
index 2c322ea58765e5763f0cd674c9509c9a9127bda9..4f4402ba3301d2e11ab20958807376c6d925ce70 100644 (file)
@@ -254,6 +254,12 @@ void smb2srv_read_recv(struct smb2srv_request *req)
        union smb_read *io;
 
        SMB2SRV_CHECK_BODY_SIZE(req, 0x30, true);
+
+       /* MS-SMB2 2.2.19 read must have a single byte of zero */
+       if (req->in.body_size - req->in.body_fixed < 1) {
+               smb2srv_send_error(req,  NT_STATUS_INVALID_PARAMETER);
+               return;
+       }
        SMB2SRV_TALLOC_IO_PTR(io, union smb_read);
        SMB2SRV_SETUP_NTVFS_REQUEST(smb2srv_read_send, NTVFS_ASYNC_STATE_MAY_ASYNC);
 
index f40bcc485c594e2f87c31b584870efe5047b69d9..ff47d594f025a4bd00a7614ed2baa64042479a67 100644 (file)
@@ -54,8 +54,13 @@ void smb2srv_keepalive_recv(struct smb2srv_request *req)
 {
        uint16_t _pad;
 
-       if (req->in.body_size < 0x04) {
-               smb2srv_send_error(req,  NT_STATUS_FOOBAR);
+       if (req->in.body_size != 0x04) {
+               smb2srv_send_error(req,  NT_STATUS_INVALID_PARAMETER);
+               return;
+       }
+
+       if (SVAL(req->in.body, 0x00) != 0x04) {
+               smb2srv_send_error(req,  NT_STATUS_INVALID_PARAMETER);
                return;
        }
 
index d64b36d659c010a98edca7b04ef68acad47fc0dd..49a2d12ef47073bdb166e2bb7bab64811ef6b97a 100644 (file)
@@ -192,7 +192,7 @@ void smb2srv_negprot_recv(struct smb2srv_request *req)
        enum ndr_err_code ndr_err;
 
        if (req->in.body_size < 0x26) {
-               smb2srv_send_error(req,  NT_STATUS_FOOBAR);
+               smbsrv_terminate_connection(req->smb_conn, "Bad body size in SMB2 negprot");
                return;
        }
 
@@ -209,7 +209,7 @@ void smb2srv_negprot_recv(struct smb2srv_request *req)
        io->in.capabilities  = IVAL(req->in.body, 0x08);
        ndr_err = smbcli_pull_guid(req->in.body, 0xC, &io->in.client_guid);
        if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
-               smbsrv_terminate_connection(req->smb_conn, nt_errstr(NT_STATUS_FOOBAR));
+               smbsrv_terminate_connection(req->smb_conn, "Bad GUID in SMB2 negprot");
                talloc_free(req);
                return;
        }
index 1fe6f0b877ef0ceb028452fdb3fa7bbf131f0fe5..c3607f0a334cb6a0a8984a0f9e87562cea113123 100644 (file)
@@ -153,7 +153,7 @@ static void smb2srv_chain_reply(struct smb2srv_request *p_req)
        chain_offset = p_req->chain_offset;
        p_req->chain_offset = 0;
 
-       if (p_req->in.size < (NBT_HDR_SIZE + chain_offset + SMB2_MIN_SIZE)) {
+       if (p_req->in.size < (NBT_HDR_SIZE + chain_offset + SMB2_MIN_SIZE_NO_BODY)) {
                DEBUG(2,("Invalid SMB2 chained packet at offset 0x%X\n",
                        chain_offset));
                smbsrv_terminate_connection(p_req->smb_conn, "Invalid SMB2 chained packet");
@@ -184,6 +184,19 @@ static void smb2srv_chain_reply(struct smb2srv_request *p_req)
        req->in.body_size       = req->in.size  - (NBT_HDR_SIZE+ chain_offset + SMB2_HDR_BODY);
        req->in.dynamic         = NULL;
 
+       req->seqnum             = BVAL(req->in.hdr, SMB2_HDR_MESSAGE_ID);
+
+       if (req->in.body_size < 2) {
+               /* error handling for this is different for negprot to 
+                  other packet types */
+               uint16_t opcode = SVAL(req->in.hdr, SMB2_HDR_OPCODE);
+               if (opcode == SMB2_OP_NEGPROT) {
+                       smbsrv_terminate_connection(req->smb_conn, "Bad body size in SMB2 negprot");                    
+               } else {
+                       smb2srv_send_error(req, NT_STATUS_INVALID_PARAMETER);
+               }
+       }
+
        buffer_code             = SVAL(req->in.body, 0);
        req->in.body_fixed      = (buffer_code & ~1);
        dynamic_size            = req->in.body_size - req->in.body_fixed;
@@ -290,6 +303,10 @@ static NTSTATUS smb2srv_reply(struct smb2srv_request *req)
        uint64_t uid;
        uint32_t flags;
 
+       if (SVAL(req->in.hdr, SMB2_HDR_LENGTH) != SMB2_HDR_BODY) {
+               smbsrv_terminate_connection(req->smb_conn, "Invalid SMB2 header length");
+               return NT_STATUS_INVALID_PARAMETER;
+       }
        opcode                  = SVAL(req->in.hdr, SMB2_HDR_OPCODE);
        req->chain_offset       = IVAL(req->in.hdr, SMB2_HDR_NEXT_COMMAND);
        req->seqnum             = BVAL(req->in.hdr, SMB2_HDR_MESSAGE_ID);
@@ -297,6 +314,13 @@ static NTSTATUS smb2srv_reply(struct smb2srv_request *req)
        uid                     = BVAL(req->in.hdr, SMB2_HDR_SESSION_ID);
        flags                   = IVAL(req->in.hdr, SMB2_HDR_FLAGS);
 
+       if (req->smb_conn->highest_smb2_seqnum != 0 &&
+           req->seqnum <= req->smb_conn->highest_smb2_seqnum) {
+               smbsrv_terminate_connection(req->smb_conn, "Invalid SMB2 sequence number");
+               return NT_STATUS_INVALID_PARAMETER;
+       }
+       req->smb_conn->highest_smb2_seqnum = req->seqnum;
+       
        req->session    = smbsrv_session_find(req->smb_conn, uid, req->request_time);
        req->tcon       = smbsrv_smb2_tcon_find(req->session, tid, req->request_time);
 
@@ -443,7 +467,7 @@ NTSTATUS smbsrv_recv_smb2_request(void *private, DATA_BLOB blob)
                return NT_STATUS_OK;
        }
 
-       if (blob.length < (NBT_HDR_SIZE + SMB2_MIN_SIZE)) {
+       if (blob.length < (NBT_HDR_SIZE + SMB2_MIN_SIZE_NO_BODY)) {
                DEBUG(2,("Invalid SMB2 packet length count %ld\n", (long)blob.length));
                smbsrv_terminate_connection(smb_conn, "Invalid SMB2 packet");
                return NT_STATUS_OK;
@@ -470,6 +494,19 @@ NTSTATUS smbsrv_recv_smb2_request(void *private, DATA_BLOB blob)
        req->in.body_size       = req->in.size  - (SMB2_HDR_BODY+NBT_HDR_SIZE);
        req->in.dynamic         = NULL;
 
+       req->seqnum             = BVAL(req->in.hdr, SMB2_HDR_MESSAGE_ID);
+
+       if (req->in.body_size < 2) {
+               /* error handling for this is different for negprot to 
+                  other packet types */
+               uint16_t opcode = SVAL(req->in.hdr, SMB2_HDR_OPCODE);
+               if (opcode == SMB2_OP_NEGPROT) {
+                       smbsrv_terminate_connection(req->smb_conn, "Bad body size in SMB2 negprot");                    
+               } else {
+                       smb2srv_send_error(req, NT_STATUS_INVALID_PARAMETER);
+               }
+       }
+
        buffer_code             = SVAL(req->in.body, 0);
        req->in.body_fixed      = (buffer_code & ~1);
        dynamic_size            = req->in.body_size - req->in.body_fixed;
index d45e0861af4a422bdb2c756c7c457623318eca61..431add4ed910bb9843962ebcf14d6dcc63b1eca9 100644 (file)
@@ -75,7 +75,7 @@ struct smbsrv_request;
 /* useful way of catching field size errors with file and line number */
 #define SMB2SRV_CHECK_BODY_SIZE(req, size, dynamic) do { \
        size_t is_size = req->in.body_size; \
-       uint16_t field_size = SVAL(req->in.body, 0); \
+       uint16_t field_size; \
        uint16_t want_size = ((dynamic)?(size)+1:(size)); \
        if (is_size < (size)) { \
                DEBUG(0,("%s: buffer too small 0x%x. Expected 0x%x\n", \
@@ -83,6 +83,7 @@ struct smbsrv_request;
                smb2srv_send_error(req,  NT_STATUS_INVALID_PARAMETER); \
                return; \
        }\
+       field_size = SVAL(req->in.body, 0);       \
        if (field_size != want_size) { \
                DEBUG(0,("%s: unexpected fixed body size 0x%x. Expected 0x%x\n", \
                         __location__, (unsigned)field_size, (unsigned)want_size)); \
index 7b3229892f79002ff3ca82f07de44f87f2150c9f..259d29039de9a4e6582edf53c53f2da6eaa7d45e 100644 (file)
@@ -52,7 +52,8 @@ static void samba3_smb_accept(struct stream_connection *conn)
        close(1);
        dup2(fd, 0);
        dup2(fd, 1);
-       for (i=2;i<256;i++) {
+       dup2(fd, 2);
+       for (i=3;i<256;i++) {
                close(i);
        }
 
index 4676fc3e9cfb1f8ffe80a4f60c70be735340223b..b3c3122765e513f9fb3a73f676a38be8fec8a44d 100644 (file)
@@ -386,6 +386,8 @@ struct smbsrv_connection {
        struct loadparm_context *lp_ctx;
 
        bool smb2_signing_required;
+
+       uint64_t highest_smb2_seqnum;
 };
 
 struct model_ops;
index a9b33a4725017fdbc36588677108c08312e8070b..6afb66ff20284c8e92734ed841e99c89e63e6999 100644 (file)
@@ -63,7 +63,8 @@ struct model_ops {
                         void *);
 
        /* function to terminate a connection or task */
-       void (*terminate)(struct event_context *, const char *reason);
+       void (*terminate)(struct event_context *, struct loadparm_context *lp_ctx, 
+                         const char *reason);
 
        /* function to set a title for the connection or task */
        void (*set_title)(struct event_context *, const char *title);
index 0d17e5301d44e6a7444cfaa5785bf9f6177424aa..1b369613ffd71eb23a4b4e07f082aaac296cdece 100644 (file)
@@ -189,7 +189,7 @@ static void prefork_new_task(struct event_context *ev,
 
 
 /* called when a task goes down */
-_NORETURN_ static void prefork_terminate(struct event_context *ev, const char *reason) 
+_NORETURN_ static void prefork_terminate(struct event_context *ev, struct loadparm_context *lp_ctx, const char *reason) 
 {
        DEBUG(2,("prefork_terminate: reason[%s]\n",reason));
 }
index a7a27ef9e0a5f34b713c7aab1a331bf80e0c6497..26afff99301549c6e3ef29dd8fac7b2b35652b6a 100644 (file)
@@ -95,7 +95,7 @@ static void single_new_task(struct event_context *ev,
 
 
 /* called when a task goes down */
-static void single_terminate(struct event_context *ev, const char *reason) 
+static void single_terminate(struct event_context *ev, struct loadparm_context *lp_ctx, const char *reason) 
 {
        DEBUG(2,("single_terminate: reason[%s]\n",reason));
 }
index c8f90209b66022bcfd69161ce01ac3b7d149ed2f..0a864dabb2a27d88684e6ca5f4fb56b24021cfc4 100644 (file)
@@ -196,13 +196,14 @@ static void standard_new_task(struct event_context *ev,
 
 
 /* called when a task goes down */
-_NORETURN_ static void standard_terminate(struct event_context *ev, const char *reason) 
+_NORETURN_ static void standard_terminate(struct event_context *ev, struct loadparm_context *lp_ctx, 
+                                         const char *reason) 
 {
        DEBUG(2,("standard_terminate: reason[%s]\n",reason));
 
        /* this reload_charcnv() has the effect of freeing the iconv context memory,
           which makes leak checking easier */
-       reload_charcnv(global_loadparm);
+       reload_charcnv(lp_ctx);
 
        talloc_free(ev);
 
index 540d956420045771be1bf83e30a1689d0f1df4b9..597cf587f13f7406980dc80b07e91a3e5b8a9cc4 100644 (file)
@@ -188,7 +188,7 @@ static void thread_new_task(struct event_context *ev,
 }
 
 /* called when a task goes down */
-static void thread_terminate(struct event_context *event_ctx, const char *reason) 
+static void thread_terminate(struct event_context *event_ctx, struct loadparm_context *lp_ctx, const char *reason) 
 {
        DEBUG(10,("thread_terminate: reason[%s]\n",reason));
 
index f27560f6ee43e6021de4a073976959e419b6a8ff..ce5b6519a11ddb493caceb64be0de93a04003651 100644 (file)
@@ -61,6 +61,8 @@ void stream_terminate_connection(struct stream_connection *srv_conn, const char
 
        if (!reason) reason = "unknown reason";
 
+       DEBUG(3,("Terminating connection - '%s'\n", reason));
+
        srv_conn->terminate = reason;
 
        if (srv_conn->processing) {
@@ -76,8 +78,8 @@ void stream_terminate_connection(struct stream_connection *srv_conn, const char
 
        talloc_free(srv_conn->event.fde);
        srv_conn->event.fde = NULL;
+       model_ops->terminate(event_ctx, srv_conn->lp_ctx, reason);
        talloc_free(srv_conn);
-       model_ops->terminate(event_ctx, reason);
 }
 
 /**
index 22746850590af7125de16f5506274551d0000246..9a2903e281ee2ee71dbf252c2de2c24c3a21d281 100644 (file)
@@ -35,7 +35,7 @@ void task_server_terminate(struct task_server *task, const char *reason)
        struct event_context *event_ctx = task->event_ctx;
        const struct model_ops *model_ops = task->model_ops;
        DEBUG(0,("task_server_terminate: [%s]\n", reason));
-       model_ops->terminate(event_ctx, reason);
+       model_ops->terminate(event_ctx, task->lp_ctx, reason);
        
        /* don't free this above, it might contain the 'reason' being printed */
        talloc_free(task);
index 24e0324bc3e303bbe5fc6554b2565e2de3527d44..c129fd586be03a1435c2123d5e3e26671f6d98e9 100644 (file)
@@ -823,6 +823,7 @@ static struct composite_context *torture_connect_async(
        smb->in.fallback_to_anonymous=false;
        smb->in.workgroup=workgroup;
        lp_smbcli_options(tctx->lp_ctx, &smb->in.options);
+       lp_smbcli_session_options(tctx->lp_ctx, &smb->in.session_options);
        
        return smb_composite_connect_send(smb,mem_ctx,
                                          lp_resolve_context(tctx->lp_ctx),ev);
index 4caeee72a47ae65188fc92b5fde42445228d5c31..ca1fd444d9e1494b55efc51f233b133b619ff9f4 100644 (file)
@@ -36,8 +36,11 @@ static bool try_failed_login(struct torture_context *tctx, struct smbcli_state *
        NTSTATUS status;
        struct smb_composite_sesssetup setup;
        struct smbcli_session *session;
+       struct smbcli_session_options options;
 
-       session = smbcli_session_init(cli->transport, cli, false);
+       lp_smbcli_session_options(tctx->lp_ctx, &options);
+
+       session = smbcli_session_init(cli->transport, cli, false, options);
        setup.in.sesskey = cli->transport->negotiate.sesskey;
        setup.in.capabilities = cli->transport->negotiate.capabilities;
        setup.in.workgroup = lp_workgroup(tctx->lp_ctx);
index 96da10b5dfeb78c07897b084e478142d3a4ed1fa..211d09756db84619a6ffe574011b58c27bd29ca0 100644 (file)
@@ -116,7 +116,7 @@ torture_rpc_OBJ_FILES = $(addprefix $(torturesrcdir)/rpc/, \
                eventlog.o epmapper.o winreg.o initshutdown.o oxidresolve.o remact.o mgmt.o \
                scanner.o autoidl.o countcalls.o testjoin.o schannel.o netlogon.o remote_pac.o samlogon.o \
                samsync.o bind.o dssetup.o alter_context.o bench.o samba3rpc.o rpc.o async_bind.o \
-               handles.o frsapi.o)
+               handles.o frsapi.o object_uuid.o)
 
 $(eval $(call proto_header_template,$(torturesrcdir)/rpc/proto.h,$(torture_rpc_OBJ_FILES:.o=.c)))
 
index 176fc035e7674510447c2ef2a38cecb2a537af37..3bf3ad8b1bf550f0346134b1be1129d36b89a75e 100644 (file)
@@ -214,7 +214,9 @@ static bool connect_servers(struct event_context *ev,
                for (j=0;j<NINSTANCES;j++) {
                        NTSTATUS status;
                        struct smbcli_options smb_options;
+                       struct smbcli_session_options smb_session_options;
                        lp_smbcli_options(lp_ctx, &smb_options);
+                       lp_smbcli_session_options(lp_ctx, &smb_session_options);
 
                        printf("Connecting to \\\\%s\\%s as %s - instance %d\n",
                               servers[i].server_name, servers[i].share_name, 
@@ -238,7 +240,8 @@ static bool connect_servers(struct event_context *ev,
                                                                     servers[i].share_name, "A:",
                                                                     servers[i].credentials,
                                                                     lp_resolve_context(lp_ctx), ev,
-                                                                    &smb_options);
+                                                                    &smb_options,
+                                                                    &smb_session_options);
                        }
                        if (!NT_STATUS_IS_OK(status)) {
                                printf("Failed to connect to \\\\%s\\%s - %s\n",
@@ -1165,6 +1168,8 @@ static void idle_func_smb2(struct smb2_transport *transport, void *private)
 */
 static bool compare_status(NTSTATUS status1, NTSTATUS status2)
 {
+       char *s;
+
        if (NT_STATUS_EQUAL(status1, status2)) return true;
 
        /* one code being an error and the other OK is always an error */
@@ -1178,6 +1183,17 @@ static bool compare_status(NTSTATUS status1, NTSTATUS status2)
            ignore_pattern(nt_errstr(status2))) {
                return true;
        }
+
+       /* also support ignore patterns of the form NT_STATUS_XX:NT_STATUS_YY
+          meaning that the first server returns NT_STATUS_XX and the 2nd
+          returns NT_STATUS_YY */
+       s = talloc_asprintf(current_op.mem_ctx, "%s:%s", 
+                           nt_errstr(status1), 
+                           nt_errstr(status2));
+       if (ignore_pattern(s)) {
+               return true;
+       }
+
        current_op.mismatch = nt_errstr(status1);
        return false;
 }
@@ -1348,7 +1364,7 @@ again:
        } \
        current_op.status = status[0]; \
        for (i=1;i<NSERVERS;i++) { \
-               if (!compare_status(status[i], status[0])) { \
+               if (!compare_status(status[0], status[1])) { \
                        printf("status different in %s - %s %s\n", #call, \
                               nt_errstr(status[0]), nt_errstr(status[i])); \
                        current_op.mismatch = nt_errstr(status[0]); \
@@ -2379,9 +2395,8 @@ static bool handler_smb_spathinfo(int instance)
        union smb_setfileinfo parm[NSERVERS];
        NTSTATUS status[NSERVERS];
 
-       parm[0].generic.in.file.path = gen_fname_open(instance);
-
        gen_setfileinfo(instance, &parm[0]);
+       parm[0].generic.in.file.path = gen_fname_open(instance);
 
        GEN_COPY_PARM;
 
@@ -2750,9 +2765,8 @@ static bool handler_smb2_sfileinfo(int instance)
        union smb_setfileinfo parm[NSERVERS];
        NTSTATUS status[NSERVERS];
 
-       parm[0].generic.in.file.fnum = gen_fnum(instance);
-
        gen_setfileinfo(instance, &parm[0]);
+       parm[0].generic.in.file.fnum = gen_fnum(instance);
 
        GEN_COPY_PARM;
        GEN_SET_FNUM_SMB2(generic.in.file.handle);
index 3730193c86fb22034eba4a6113d56944aba4f8e8..23b0554c4f65ecc7eb0688083baeaea8171355ae 100644 (file)
@@ -64,7 +64,7 @@ static bool test_cldap_netlogon(struct torture_context *tctx, const char *dest)
        n1 = search.out.netlogon;
 
        search.in.user         = "Administrator";
-       search.in.realm        = n1.nt5_ex.dns_domain;
+       search.in.realm        = n1.data.nt5_ex.dns_domain;
        search.in.host         = "__cldap_torture__";
 
        printf("Scanning for netlogon levels\n");
@@ -93,8 +93,8 @@ static bool test_cldap_netlogon(struct torture_context *tctx, const char *dest)
        search.in.user = NULL;
        status = cldap_netlogon(cldap, tctx, &search);
        CHECK_STATUS(status, NT_STATUS_OK);
-       CHECK_STRING(search.out.netlogon.nt5_ex.user_name, "");
-       CHECK_VAL(search.out.netlogon.nt5_ex.command, LOGON_SAM_LOGON_RESPONSE_EX);
+       CHECK_STRING(search.out.netlogon.data.nt5_ex.user_name, "");
+       CHECK_VAL(search.out.netlogon.data.nt5_ex.command, LOGON_SAM_LOGON_RESPONSE_EX);
 
        printf("Trying with User=Administrator\n");
 
@@ -102,8 +102,8 @@ static bool test_cldap_netlogon(struct torture_context *tctx, const char *dest)
        status = cldap_netlogon(cldap, tctx, &search);
        CHECK_STATUS(status, NT_STATUS_OK);
 
-       CHECK_STRING(search.out.netlogon.nt5_ex.user_name, search.in.user);
-       CHECK_VAL(search.out.netlogon.nt5_ex.command, LOGON_SAM_LOGON_USER_UNKNOWN_EX);
+       CHECK_STRING(search.out.netlogon.data.nt5_ex.user_name, search.in.user);
+       CHECK_VAL(search.out.netlogon.data.nt5_ex.command, LOGON_SAM_LOGON_USER_UNKNOWN_EX);
 
        search.in.version = NETLOGON_NT_VERSION_5;
        status = cldap_netlogon(cldap, tctx, &search);
@@ -114,8 +114,8 @@ static bool test_cldap_netlogon(struct torture_context *tctx, const char *dest)
        search.in.user = NULL;
        status = cldap_netlogon(cldap, tctx, &search);
        CHECK_STATUS(status, NT_STATUS_OK);
-       CHECK_STRING(search.out.netlogon.nt5_ex.user_name, "");
-       CHECK_VAL(search.out.netlogon.nt5_ex.command, LOGON_SAM_LOGON_RESPONSE);
+       CHECK_STRING(search.out.netlogon.data.nt5_ex.user_name, "");
+       CHECK_VAL(search.out.netlogon.data.nt5_ex.command, LOGON_SAM_LOGON_RESPONSE);
 
        printf("Trying with User=Administrator\n");
 
@@ -123,18 +123,18 @@ static bool test_cldap_netlogon(struct torture_context *tctx, const char *dest)
        status = cldap_netlogon(cldap, tctx, &search);
        CHECK_STATUS(status, NT_STATUS_OK);
 
-       CHECK_STRING(search.out.netlogon.nt5_ex.user_name, search.in.user);
-       CHECK_VAL(search.out.netlogon.nt5_ex.command, LOGON_SAM_LOGON_USER_UNKNOWN);
+       CHECK_STRING(search.out.netlogon.data.nt5_ex.user_name, search.in.user);
+       CHECK_VAL(search.out.netlogon.data.nt5_ex.command, LOGON_SAM_LOGON_USER_UNKNOWN);
 
        search.in.version = NETLOGON_NT_VERSION_5 | NETLOGON_NT_VERSION_5EX;
 
        printf("Trying with a GUID\n");
        search.in.realm       = NULL;
-       search.in.domain_guid = GUID_string(tctx, &n1.nt5_ex.domain_uuid);
+       search.in.domain_guid = GUID_string(tctx, &n1.data.nt5_ex.domain_uuid);
        status = cldap_netlogon(cldap, tctx, &search);
        CHECK_STATUS(status, NT_STATUS_OK);
-       CHECK_VAL(search.out.netlogon.nt5_ex.command, LOGON_SAM_LOGON_USER_UNKNOWN_EX);
-       CHECK_STRING(GUID_string(tctx, &search.out.netlogon.nt5_ex.domain_uuid), search.in.domain_guid);
+       CHECK_VAL(search.out.netlogon.data.nt5_ex.command, LOGON_SAM_LOGON_USER_UNKNOWN_EX);
+       CHECK_STRING(GUID_string(tctx, &search.out.netlogon.data.nt5_ex.domain_uuid), search.in.domain_guid);
 
        printf("Trying with a incorrect GUID\n");
        guid = GUID_random();
@@ -145,53 +145,53 @@ static bool test_cldap_netlogon(struct torture_context *tctx, const char *dest)
 
        printf("Trying with a AAC\n");
        search.in.acct_control = ACB_WSTRUST|ACB_SVRTRUST;
-       search.in.realm = n1.nt5_ex.dns_domain;
+       search.in.realm = n1.data.nt5_ex.dns_domain;
        status = cldap_netlogon(cldap, tctx, &search);
        CHECK_STATUS(status, NT_STATUS_OK);
-       CHECK_VAL(search.out.netlogon.nt5_ex.command, LOGON_SAM_LOGON_RESPONSE_EX);
-       CHECK_STRING(search.out.netlogon.nt5_ex.user_name, "");
+       CHECK_VAL(search.out.netlogon.data.nt5_ex.command, LOGON_SAM_LOGON_RESPONSE_EX);
+       CHECK_STRING(search.out.netlogon.data.nt5_ex.user_name, "");
 
        printf("Trying with a zero AAC\n");
        search.in.acct_control = 0x0;
-       search.in.realm = n1.nt5_ex.dns_domain;
+       search.in.realm = n1.data.nt5_ex.dns_domain;
        status = cldap_netlogon(cldap, tctx, &search);
        CHECK_STATUS(status, NT_STATUS_OK);
-       CHECK_VAL(search.out.netlogon.nt5_ex.command, LOGON_SAM_LOGON_RESPONSE_EX);
-       CHECK_STRING(search.out.netlogon.nt5_ex.user_name, "");
+       CHECK_VAL(search.out.netlogon.data.nt5_ex.command, LOGON_SAM_LOGON_RESPONSE_EX);
+       CHECK_STRING(search.out.netlogon.data.nt5_ex.user_name, "");
 
        printf("Trying with a zero AAC and user=Administrator\n");
        search.in.acct_control = 0x0;
        search.in.user = "Administrator";
-       search.in.realm = n1.nt5_ex.dns_domain;
+       search.in.realm = n1.data.nt5_ex.dns_domain;
        status = cldap_netlogon(cldap, tctx, &search);
        CHECK_STATUS(status, NT_STATUS_OK);
-       CHECK_VAL(search.out.netlogon.nt5_ex.command, LOGON_SAM_LOGON_USER_UNKNOWN_EX);
-       CHECK_STRING(search.out.netlogon.nt5_ex.user_name, "Administrator");
+       CHECK_VAL(search.out.netlogon.data.nt5_ex.command, LOGON_SAM_LOGON_USER_UNKNOWN_EX);
+       CHECK_STRING(search.out.netlogon.data.nt5_ex.user_name, "Administrator");
 
        printf("Trying with a bad AAC\n");
        search.in.user = NULL;
        search.in.acct_control = 0xFF00FF00;
-       search.in.realm = n1.nt5_ex.dns_domain;
+       search.in.realm = n1.data.nt5_ex.dns_domain;
        status = cldap_netlogon(cldap, tctx, &search);
        CHECK_STATUS(status, NT_STATUS_OK);
-       CHECK_VAL(search.out.netlogon.nt5_ex.command, LOGON_SAM_LOGON_RESPONSE_EX);
-       CHECK_STRING(search.out.netlogon.nt5_ex.user_name, "");
+       CHECK_VAL(search.out.netlogon.data.nt5_ex.command, LOGON_SAM_LOGON_RESPONSE_EX);
+       CHECK_STRING(search.out.netlogon.data.nt5_ex.user_name, "");
 
        printf("Trying with a user only\n");
        search = empty_search;
        search.in.user = "Administrator";
        status = cldap_netlogon(cldap, tctx, &search);
        CHECK_STATUS(status, NT_STATUS_OK);
-       CHECK_STRING(search.out.netlogon.nt5_ex.dns_domain, n1.nt5_ex.dns_domain);
-       CHECK_STRING(search.out.netlogon.nt5_ex.user_name, search.in.user);
+       CHECK_STRING(search.out.netlogon.data.nt5_ex.dns_domain, n1.data.nt5_ex.dns_domain);
+       CHECK_STRING(search.out.netlogon.data.nt5_ex.user_name, search.in.user);
 
        printf("Trying with just a bad username\n");
        search.in.user = "___no_such_user___";
        status = cldap_netlogon(cldap, tctx, &search);
        CHECK_STATUS(status, NT_STATUS_OK);
-       CHECK_STRING(search.out.netlogon.nt5_ex.user_name, search.in.user);
-       CHECK_STRING(search.out.netlogon.nt5_ex.dns_domain, n1.nt5_ex.dns_domain);
-       CHECK_VAL(search.out.netlogon.nt5_ex.command, LOGON_SAM_LOGON_USER_UNKNOWN_EX);
+       CHECK_STRING(search.out.netlogon.data.nt5_ex.user_name, search.in.user);
+       CHECK_STRING(search.out.netlogon.data.nt5_ex.dns_domain, n1.data.nt5_ex.dns_domain);
+       CHECK_VAL(search.out.netlogon.data.nt5_ex.command, LOGON_SAM_LOGON_USER_UNKNOWN_EX);
 
        printf("Trying with just a bad domain\n");
        search = empty_search;
@@ -200,29 +200,29 @@ static bool test_cldap_netlogon(struct torture_context *tctx, const char *dest)
        CHECK_STATUS(status, NT_STATUS_NOT_FOUND);
 
        printf("Trying with a incorrect domain and correct guid\n");
-       search.in.domain_guid = GUID_string(tctx, &n1.nt5_ex.domain_uuid);
+       search.in.domain_guid = GUID_string(tctx, &n1.data.nt5_ex.domain_uuid);
        status = cldap_netlogon(cldap, tctx, &search);
        CHECK_STATUS(status, NT_STATUS_OK);
-       CHECK_STRING(search.out.netlogon.nt5_ex.dns_domain, n1.nt5_ex.dns_domain);
-       CHECK_STRING(search.out.netlogon.nt5_ex.user_name, "");
-       CHECK_VAL(search.out.netlogon.nt5_ex.command, LOGON_SAM_LOGON_RESPONSE_EX);
+       CHECK_STRING(search.out.netlogon.data.nt5_ex.dns_domain, n1.data.nt5_ex.dns_domain);
+       CHECK_STRING(search.out.netlogon.data.nt5_ex.user_name, "");
+       CHECK_VAL(search.out.netlogon.data.nt5_ex.command, LOGON_SAM_LOGON_RESPONSE_EX);
 
        printf("Trying with a incorrect domain and incorrect guid\n");
        search.in.domain_guid = GUID_string(tctx, &guid);
        status = cldap_netlogon(cldap, tctx, &search);
        CHECK_STATUS(status, NT_STATUS_NOT_FOUND);
-       CHECK_STRING(search.out.netlogon.nt5_ex.dns_domain, n1.nt5_ex.dns_domain);
-       CHECK_STRING(search.out.netlogon.nt5_ex.user_name, "");
-       CHECK_VAL(search.out.netlogon.nt5_ex.command, LOGON_SAM_LOGON_RESPONSE_EX);
+       CHECK_STRING(search.out.netlogon.data.nt5_ex.dns_domain, n1.data.nt5_ex.dns_domain);
+       CHECK_STRING(search.out.netlogon.data.nt5_ex.user_name, "");
+       CHECK_VAL(search.out.netlogon.data.nt5_ex.command, LOGON_SAM_LOGON_RESPONSE_EX);
 
        printf("Trying with a incorrect GUID and correct domain\n");
        search.in.domain_guid = GUID_string(tctx, &guid);
-       search.in.realm = n1.nt5_ex.dns_domain;
+       search.in.realm = n1.data.nt5_ex.dns_domain;
        status = cldap_netlogon(cldap, tctx, &search);
        CHECK_STATUS(status, NT_STATUS_OK);
-       CHECK_STRING(search.out.netlogon.nt5_ex.dns_domain, n1.nt5_ex.dns_domain);
-       CHECK_STRING(search.out.netlogon.nt5_ex.user_name, "");
-       CHECK_VAL(search.out.netlogon.nt5_ex.command, LOGON_SAM_LOGON_RESPONSE_EX);
+       CHECK_STRING(search.out.netlogon.data.nt5_ex.dns_domain, n1.data.nt5_ex.dns_domain);
+       CHECK_STRING(search.out.netlogon.data.nt5_ex.user_name, "");
+       CHECK_VAL(search.out.netlogon.data.nt5_ex.command, LOGON_SAM_LOGON_RESPONSE_EX);
 
        return true;
 }
@@ -255,9 +255,9 @@ static bool test_cldap_netlogon_flags(struct torture_context *tctx,
 
        n1 = search.out.netlogon;
        if (n1.ntver == NETLOGON_NT_VERSION_5)
-               server_type = n1.nt5.server_type;
+               server_type = n1.data.nt5.server_type;
        else if (n1.ntver == NETLOGON_NT_VERSION_5EX)
-               server_type = n1.nt5_ex.server_type;    
+               server_type = n1.data.nt5_ex.server_type;       
 
        printf("The word is: %i\n", server_type);
        if (server_type & NBT_SERVER_PDC)
@@ -366,9 +366,9 @@ static bool test_cldap_netlogon_flag_ds_dns_forest(struct torture_context *tctx,
 
        n1 = search.out.netlogon;
        if (n1.ntver == NETLOGON_NT_VERSION_5)
-               server_type = n1.nt5.server_type;
+               server_type = n1.data.nt5.server_type;
        else if (n1.ntver == NETLOGON_NT_VERSION_5EX)
-               server_type = n1.nt5_ex.server_type;
+               server_type = n1.data.nt5_ex.server_type;
 
        if (server_type & NBT_SERVER_DS_DNS_FOREST) {
                struct cldap_search search2;
index dd1d2de33163b367753e310c951742e2a8d58ced..fdb4251c15ea8e2505c7ef77ad18315a1da54ad4 100644 (file)
@@ -41,6 +41,8 @@ struct test_rootDSE {
 };
 
 struct test_schema_ctx {
+       struct ldb_context *ldb;
+
        struct ldb_paged_control *ctrl;
        uint32_t count;
        bool pending;
@@ -82,15 +84,24 @@ static bool test_search_rootDSE(struct ldb_context *ldb, struct test_rootDSE *ro
        return true;
 }
 
-static int test_schema_search_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares)
+static int test_schema_search_callback(struct ldb_request *req, struct ldb_reply *ares)
 {
-       struct test_schema_ctx *actx = talloc_get_type(context, struct test_schema_ctx);
+       struct test_schema_ctx *actx;
        int ret = LDB_SUCCESS;
 
+       actx = talloc_get_type(req->context, struct test_schema_ctx);
+
+       if (!ares) {
+               return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_request_done(req, ares->error);
+       }
+
        switch (ares->type) {
        case LDB_REPLY_ENTRY:
                actx->count++;
-               ret = actx->callback(actx->private_data, ldb, ares->message);
+               ret = actx->callback(actx->private_data, actx->ldb, ares->message);
                break;
 
        case LDB_REPLY_REFERRAL:
@@ -118,21 +129,22 @@ static int test_schema_search_callback(struct ldb_context *ldb, void *context, s
                                actx->pending = true;
                        }
                }
-               break;
-               
+               talloc_free(ares);
+               return ldb_request_done(req, LDB_SUCCESS);
+
        default:
                d_printf("%s: unknown Reply Type %u\n", __location__, ares->type);
-               return LDB_ERR_OTHER;
+               return ldb_request_done(req, LDB_ERR_OTHER);
        }
 
        if (talloc_free(ares) == -1) {
                d_printf("talloc_free failed\n");
                actx->pending = 0;
-               return LDB_ERR_OPERATIONS_ERROR;
+               return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
        }
 
        if (ret) {
-               return LDB_ERR_OPERATIONS_ERROR;
+               return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
        }
 
        return LDB_SUCCESS;
@@ -149,10 +161,12 @@ static bool test_create_schema_type(struct ldb_context *ldb, struct test_rootDSE
        int ret;
        struct test_schema_ctx *actx;
 
-       req = talloc(ldb, struct ldb_request);
-       actx = talloc(req, struct test_schema_ctx);
+       actx = talloc(ldb, struct test_schema_ctx);
+       actx->ldb = ldb;
+       actx->private_data = private_data;
+       actx->callback= callback;
 
-       ctrl = talloc_array(req, struct ldb_control *, 2);
+       ctrl = talloc_array(actx, struct ldb_control *, 2);
        ctrl[0] = talloc(ctrl, struct ldb_control);
        ctrl[0]->oid = LDB_CONTROL_PAGED_RESULTS_OID;
        ctrl[0]->critical = true;
@@ -163,33 +177,30 @@ static bool test_create_schema_type(struct ldb_context *ldb, struct test_rootDSE
        ctrl[0]->data = control;
        ctrl[1] = NULL;
 
-       req->operation = LDB_SEARCH;
-       req->op.search.base = ldb_dn_new(req, ldb, root->schemadn);
-       req->op.search.scope = LDB_SCOPE_SUBTREE;
-       req->op.search.tree = ldb_parse_tree(req, filter);
-       if (req->op.search.tree == NULL) return -1;
-       req->op.search.attrs = NULL;
-       req->controls = ctrl;
-       req->context = actx;
-       req->callback = test_schema_search_callback;
-       ldb_set_timeout(ldb, req, 0);
-
-       actx->count             = 0;
-       actx->ctrl              = control;
-       actx->callback          = callback;
-       actx->private_data      = private_data;
+       ret = ldb_build_search_req(&req, ldb, actx,
+                                  ldb_dn_new(actx, ldb, root->schemadn),
+                                  LDB_SCOPE_SUBTREE,
+                                  filter, NULL,
+                                  ctrl,
+                                  actx, test_schema_search_callback,
+                                  NULL);
+
+       actx->ctrl = control;
+       actx->count = 0;
 again:
        actx->pending           = false;
 
        ret = ldb_request(ldb, req);
        if (ret != LDB_SUCCESS) {
                d_printf("search failed - %s\n", ldb_errstring(ldb));
+               talloc_free(actx);
                return false;
        }
 
        ret = ldb_wait(req->handle, LDB_WAIT_ALL);
                if (ret != LDB_SUCCESS) {
                d_printf("search error - %s\n", ldb_errstring(ldb));
+               talloc_free(actx);
                return false;
        }
 
@@ -197,6 +208,7 @@ again:
                goto again;
 
        d_printf("filter[%s] count[%u]\n", filter, actx->count);
+       talloc_free(actx);
        return true;
 }
 
index 9c7bffb6f4c99ce286fa084b7e46de7da57de0ff..a511e261cb9606dd74718ef9bf4179b6cf96351e 100644 (file)
@@ -117,8 +117,10 @@ static struct smbcli_state *connect_one(struct event_context *ev,
        NTSTATUS status;
        int retries = 10;
        struct smbcli_options options;
+       struct smbcli_session_options session_options;
 
        lp_smbcli_options(lp_ctx, &options);
+       lp_smbcli_session_options(lp_ctx, &session_options);
 
        printf("connect_one(%s, %d, %d)\n", share, snum, conn);
 
@@ -164,7 +166,7 @@ static struct smbcli_state *connect_one(struct event_context *ev,
                                                share, NULL,
                                                servers[snum], 
                                                lp_resolve_context(lp_ctx),
-                                               ev, &options);
+                                               ev, &options, &session_options);
                if (!NT_STATUS_IS_OK(status)) {
                        sleep(2);
                }
index e6c4728f0ddf854aba43b39ff2af1371a6a86f8b..b49b8d256ab164d33d3c3d079d5793870b96c51d 100644 (file)
@@ -138,7 +138,8 @@ static bool try_unlock(struct smbcli_state *c, int fstype,
 return a connection to a server
 *******************************************************/
 static struct smbcli_state *connect_one(char *share, const char **ports,
-                                       struct smb_options *optionsi,
+                                       struct smb_options *options,
+                                       struct smb_options *session_options,
                                        struct event_context *ev)
 {
        struct smbcli_state *c;
@@ -168,7 +169,7 @@ static struct smbcli_state *connect_one(char *share, const char **ports,
        nt_status = smbcli_full_connection(NULL, 
                           &c, myname, server_n, ports, share, NULL,
                           username, lp_workgroup(), password, ev,
-                          options);
+                          options, session_options);
        if (!NT_STATUS_IS_OK(nt_status)) {
                DEBUG(0, ("smbcli_full_connection failed with error %s\n", nt_errstr(nt_status)));
                return NULL;
@@ -185,6 +186,7 @@ static void reconnect(struct smbcli_state *cli[NSERVERS][NCONNECTIONS],
                      int fnum[NSERVERS][NUMFSTYPES][NCONNECTIONS][NFILES],
                      const char **ports,
                      struct smbcli_options *options,
+                     struct smbcli_session_options *session_options,
                      struct event_context *ev,
                      char *share1, char *share2)
 {
@@ -204,7 +206,7 @@ static void reconnect(struct smbcli_state *cli[NSERVERS][NCONNECTIONS],
                        smbcli_ulogoff(cli[server][conn]);
                        talloc_free(cli[server][conn]);
                }
-               cli[server][conn] = connect_one(share[server], ports, options, ev);
+               cli[server][conn] = connect_one(share[server], ports, options, session_options, ev);
                if (!cli[server][conn]) {
                        DEBUG(0,("Failed to connect to %s\n", share[server]));
                        exit(1);
@@ -354,6 +356,7 @@ static void test_locks(char *share1, char *share2,
                        char *nfspath1, char *nfspath2,
                        const char **ports,
                        struct smbcli_options *options,
+                       struct smbcli_session_options *session_options,
                        struct event_context *ev)
 {
        struct smbcli_state *cli[NSERVERS][NCONNECTIONS];
@@ -383,7 +386,7 @@ static void test_locks(char *share1, char *share2,
                recorded[n].needed = true;
        }
 
-       reconnect(cli, nfs, fnum, ports, options, ev, share1, share2);
+       reconnect(cli, nfs, fnum, ports, options, session_options, ev, share1, share2);
        open_files(cli, nfs, fnum);
        n = retest(cli, nfs, fnum, numops);
 
@@ -394,7 +397,7 @@ static void test_locks(char *share1, char *share2,
                n1 = n;
 
                close_files(cli, nfs, fnum);
-               reconnect(cli, nfs, fnum, ports, options, ev, share1, share2);
+               reconnect(cli, nfs, fnum, ports, options, session_options, ev, share1, share2);
                open_files(cli, nfs, fnum);
 
                for (i=0;i<n-1;i++) {
@@ -421,7 +424,7 @@ static void test_locks(char *share1, char *share2,
        }
 
        close_files(cli, nfs, fnum);
-       reconnect(cli, nfs, fnum, ports, options, ev, share1, share2);
+       reconnect(cli, nfs, fnum, ports, options, session_options, ev, share1, share2);
        open_files(cli, nfs, fnum);
        showall = true;
        n1 = retest(cli, nfs, fnum, n);
@@ -469,6 +472,7 @@ static void usage(void)
        extern char *optarg;
        extern int optind;
        struct smbcli_options options;
+       struct smbcli_session_options session_options;
        int opt;
        char *p;
        int seed;
@@ -554,8 +558,9 @@ static void usage(void)
 
        locking_init(1);
        lp_smbcli_options(lp_ctx, &options);
+       lp_smbcli_session_options(lp_ctx, &session_options);
        test_locks(share1, share2, nfspath1, nfspath2, lp_smb_ports(lp_ctx),
-                  &options, ev);
+                  &options, &session_options, ev);
 
        return(0);
 }
index 35e9a57fe82bd1fcb8956bf142cfbfd65e32e3a2..a739a1e1b5b6baa66ba3196e87ab6d15d6f406dc 100644 (file)
@@ -76,7 +76,8 @@ return a connection to a server
 static struct smbcli_state *connect_one(struct resolve_context *resolve_ctx, 
                                        struct event_context *ev,
                                        char *share, const char **ports,
-                                       struct smbcli_options *options)
+                                       struct smbcli_options *options,
+                                       struct smbcli_session_options *session_options)
 {
        struct smbcli_state *c;
        fstring server;
@@ -95,7 +96,7 @@ static struct smbcli_state *connect_one(struct resolve_context *resolve_ctx,
                                        ports,
                                        share, NULL,
                                        cmdline_credentials, resolve_ctx, ev,
-                                       options);
+                                       options, session_options);
 
        if (!NT_STATUS_IS_OK(status)) {
                return NULL;
@@ -296,6 +297,7 @@ static void usage(poptContext pc)
        struct event_context *ev;
        struct loadparm_context *lp_ctx;
        struct smbcli_options options;
+       struct smbcli_session_options session_options;
        poptContext pc;
        int argc_new, i;
        char **argv_new;
@@ -360,9 +362,10 @@ static void usage(poptContext pc)
        gensec_init(lp_ctx);
 
        lp_smbcli_options(lp_ctx, &options);
+       lp_smbcli_session_options(lp_ctx, &session_options);
 
        cli = connect_one(lp_resolve_context(lp_ctx), ev, share, 
-                         lp_smb_ports(lp_ctx), &options);
+                         lp_smb_ports(lp_ctx), &options, &session_options);
        if (!cli) {
                DEBUG(0,("Failed to connect to %s\n", share));
                exit(1);
index eac2b1fe30951169663a50f66ba1edefb6848408..5d26d65e0c0f25b1d296fca42af38cab6b92acfd 100644 (file)
@@ -148,7 +148,7 @@ static bool nbt_test_netlogon(struct torture_context *tctx)
        torture_assert(tctx, response != NULL, "Failed to receive a netlogon reply packet");
 
        torture_assert(tctx, response->response_type == NETLOGON_GET_PDC, "Got incorrect type of netlogon response");
-       torture_assert(tctx, response->get_pdc.command == NETLOGON_RESPONSE_FROM_PDC, "Got incorrect netlogon response command");
+       torture_assert(tctx, response->data.get_pdc.command == NETLOGON_RESPONSE_FROM_PDC, "Got incorrect netlogon response command");
 
        return true;
 }
@@ -243,10 +243,10 @@ static bool nbt_test_netlogon2(struct torture_context *tctx)
        torture_assert(tctx, response != NULL, "Failed to receive a netlogon reply packet");
 
        torture_assert_int_equal(tctx, response->response_type, NETLOGON_SAMLOGON, "Got incorrect type of netlogon response");
-       map_netlogon_samlogon_response(&response->samlogon);
+       map_netlogon_samlogon_response(&response->data.samlogon);
 
-       torture_assert_int_equal(tctx, response->samlogon.nt5_ex.command, LOGON_SAM_LOGON_RESPONSE_EX, "Got incorrect netlogon response command");
-       torture_assert_int_equal(tctx, response->samlogon.nt5_ex.nt_version, NETLOGON_NT_VERSION_5EX_WITH_IP|NETLOGON_NT_VERSION_5EX|NETLOGON_NT_VERSION_1, "Got incorrect netlogon response command");
+       torture_assert_int_equal(tctx, response->data.samlogon.data.nt5_ex.command, LOGON_SAM_LOGON_RESPONSE_EX, "Got incorrect netlogon response command");
+       torture_assert_int_equal(tctx, response->data.samlogon.data.nt5_ex.nt_version, NETLOGON_NT_VERSION_5EX_WITH_IP|NETLOGON_NT_VERSION_5EX|NETLOGON_NT_VERSION_1, "Got incorrect netlogon response command");
 
        /* setup (another) temporary mailslot listener for replies */
        dgmslot = dgram_mailslot_temp(dgmsock, NBT_MAILSLOT_GETDC,
@@ -282,11 +282,11 @@ static bool nbt_test_netlogon2(struct torture_context *tctx)
        torture_assert(tctx, response != NULL, "Failed to receive a netlogon reply packet");
 
        torture_assert_int_equal(tctx, response->response_type, NETLOGON_SAMLOGON, "Got incorrect type of netlogon response");
-       map_netlogon_samlogon_response(&response->samlogon);
+       map_netlogon_samlogon_response(&response->data.samlogon);
 
-       torture_assert_int_equal(tctx, response->samlogon.nt5_ex.command, LOGON_SAM_LOGON_USER_UNKNOWN, "Got incorrect netlogon response command");
+       torture_assert_int_equal(tctx, response->data.samlogon.data.nt5_ex.command, LOGON_SAM_LOGON_USER_UNKNOWN, "Got incorrect netlogon response command");
 
-       torture_assert_str_equal(tctx, response->samlogon.nt5_ex.user_name, TEST_NAME"$", "Got incorrect user in netlogon response");
+       torture_assert_str_equal(tctx, response->data.samlogon.data.nt5_ex.user_name, TEST_NAME"$", "Got incorrect user in netlogon response");
 
        join_ctx = torture_join_domain(tctx, TEST_NAME, 
                                       ACB_WSTRUST, &machine_credentials);
@@ -333,9 +333,9 @@ static bool nbt_test_netlogon2(struct torture_context *tctx)
        torture_assert(tctx, response != NULL, "Failed to receive a netlogon reply packet");
 
        torture_assert_int_equal(tctx, response->response_type, NETLOGON_SAMLOGON, "Got incorrect type of netlogon response");
-       map_netlogon_samlogon_response(&response->samlogon);
+       map_netlogon_samlogon_response(&response->data.samlogon);
 
-       torture_assert_int_equal(tctx, response->samlogon.nt5_ex.command, LOGON_SAM_LOGON_USER_UNKNOWN, "Got incorrect netlogon response command");
+       torture_assert_int_equal(tctx, response->data.samlogon.data.nt5_ex.command, LOGON_SAM_LOGON_USER_UNKNOWN, "Got incorrect netlogon response command");
 
        /* setup (another) temporary mailslot listener for replies */
        dgmslot = dgram_mailslot_temp(dgmsock, NBT_MAILSLOT_GETDC,
@@ -374,9 +374,9 @@ static bool nbt_test_netlogon2(struct torture_context *tctx)
        torture_assert(tctx, response != NULL, "Failed to receive a netlogon reply packet");
 
        torture_assert_int_equal(tctx, response->response_type, NETLOGON_SAMLOGON, "Got incorrect type of netlogon response");
-       map_netlogon_samlogon_response(&response->samlogon);
+       map_netlogon_samlogon_response(&response->data.samlogon);
 
-       torture_assert_int_equal(tctx, response->samlogon.nt5_ex.command, LOGON_SAM_LOGON_RESPONSE, "Got incorrect netlogon response command");
+       torture_assert_int_equal(tctx, response->data.samlogon.data.nt5_ex.command, LOGON_SAM_LOGON_RESPONSE, "Got incorrect netlogon response command");
 
        dgmslot->private = NULL;
 
@@ -413,9 +413,9 @@ static bool nbt_test_netlogon2(struct torture_context *tctx)
        torture_assert(tctx, response != NULL, "Failed to receive a netlogon reply packet");
 
        torture_assert_int_equal(tctx, response->response_type, NETLOGON_SAMLOGON, "Got incorrect type of netlogon response");
-       map_netlogon_samlogon_response(&response->samlogon);
+       map_netlogon_samlogon_response(&response->data.samlogon);
 
-       torture_assert_int_equal(tctx, response->samlogon.nt5_ex.command, LOGON_SAM_LOGON_USER_UNKNOWN, "Got incorrect netlogon response command");
+       torture_assert_int_equal(tctx, response->data.samlogon.data.nt5_ex.command, LOGON_SAM_LOGON_USER_UNKNOWN, "Got incorrect netlogon response command");
 
        torture_leave_domain(tctx, join_ctx);
        return true;
@@ -522,11 +522,11 @@ static bool nbt_test_ntlogon(struct torture_context *tctx)
        torture_assert(tctx, response != NULL, "Failed to receive a netlogon reply packet");
 
        torture_assert_int_equal(tctx, response->response_type, NETLOGON_SAMLOGON, "Got incorrect type of netlogon response");
-       map_netlogon_samlogon_response(&response->samlogon);
+       map_netlogon_samlogon_response(&response->data.samlogon);
 
-       torture_assert_int_equal(tctx, response->samlogon.nt5_ex.command, LOGON_SAM_LOGON_RESPONSE, "Got incorrect netlogon response command");
+       torture_assert_int_equal(tctx, response->data.samlogon.data.nt5_ex.command, LOGON_SAM_LOGON_RESPONSE, "Got incorrect netlogon response command");
 
-       torture_assert_str_equal(tctx, response->samlogon.nt5_ex.user_name, TEST_NAME"$", "Got incorrect user in netlogon response");
+       torture_assert_str_equal(tctx, response->data.samlogon.data.nt5_ex.user_name, TEST_NAME"$", "Got incorrect user in netlogon response");
 
 
        /* setup a temporary mailslot listener for replies */
@@ -566,11 +566,11 @@ static bool nbt_test_ntlogon(struct torture_context *tctx)
        torture_assert(tctx, response != NULL, "Failed to receive a netlogon reply packet");
 
        torture_assert_int_equal(tctx, response->response_type, NETLOGON_SAMLOGON, "Got incorrect type of netlogon response");
-       map_netlogon_samlogon_response(&response->samlogon);
+       map_netlogon_samlogon_response(&response->data.samlogon);
 
-       torture_assert_int_equal(tctx, response->samlogon.nt5_ex.command, LOGON_SAM_LOGON_RESPONSE, "Got incorrect netlogon response command");
+       torture_assert_int_equal(tctx, response->data.samlogon.data.nt5_ex.command, LOGON_SAM_LOGON_RESPONSE, "Got incorrect netlogon response command");
 
-       torture_assert_str_equal(tctx, response->samlogon.nt5_ex.user_name, TEST_NAME"$", "Got incorrect user in netlogon response");
+       torture_assert_str_equal(tctx, response->data.samlogon.data.nt5_ex.user_name, TEST_NAME"$", "Got incorrect user in netlogon response");
 
 
        /* setup (another) temporary mailslot listener for replies */
@@ -606,7 +606,7 @@ static bool nbt_test_ntlogon(struct torture_context *tctx)
        torture_assert(tctx, response != NULL, "Failed to receive a netlogon reply packet");
 
        torture_assert_int_equal(tctx, response->response_type, NETLOGON_GET_PDC, "Got incorrect type of ntlogon response");
-       torture_assert_int_equal(tctx, response->get_pdc.command, NETLOGON_RESPONSE_FROM_PDC, "Got incorrect ntlogon response command");
+       torture_assert_int_equal(tctx, response->data.get_pdc.command, NETLOGON_RESPONSE_FROM_PDC, "Got incorrect ntlogon response command");
 
        torture_leave_domain(tctx, join_ctx);
 
@@ -643,7 +643,7 @@ static bool nbt_test_ntlogon(struct torture_context *tctx)
        torture_assert(tctx, response != NULL, "Failed to receive a netlogon reply packet");
 
        torture_assert_int_equal(tctx, response->response_type, NETLOGON_GET_PDC, "Got incorrect type of ntlogon response");
-       torture_assert_int_equal(tctx, response->get_pdc.command, NETLOGON_RESPONSE_FROM_PDC, "Got incorrect ntlogon response command");
+       torture_assert_int_equal(tctx, response->data.get_pdc.command, NETLOGON_RESPONSE_FROM_PDC, "Got incorrect ntlogon response command");
 
 
        return true;
index a72a03fa3858ed0e80cba95003257553a1bbf1fa..0d6d78688248d35d1917cc259784bc06223277be 100644 (file)
@@ -1538,8 +1538,8 @@ static bool lsarlookupnames2_in_check(struct torture_context *tctx,
        torture_assert_str_equal(tctx, r->in.names[1].string, "Administrators", 
                                                         "names[1]");
        torture_assert_int_equal(tctx, r->in.level, 1, "level");
-       torture_assert_int_equal(tctx, r->in.unknown1, 0, "unknown 1");
-       torture_assert_int_equal(tctx, r->in.unknown2, 0, "unknown 2");
+       torture_assert_int_equal(tctx, r->in.lookup_options, 0, "lookup_options");
+       torture_assert_int_equal(tctx, r->in.client_revision, 0, "client_revision");
        torture_assert_int_equal(tctx, *r->in.count, 0, "count");
        torture_assert_int_equal(tctx, r->in.sids->count, 0, "sids count");
        torture_assert(tctx, r->in.sids->sids == NULL, "sids sids");
@@ -1637,8 +1637,8 @@ static bool lsarlookupnames3_in_check(struct torture_context *tctx,
        torture_assert_str_equal(tctx, r->in.names[1].string, "Administrators", 
                                                         "names[1]");
        torture_assert_int_equal(tctx, r->in.level, 1, "level");
-       torture_assert_int_equal(tctx, r->in.unknown1, 0, "unknown 1");
-       torture_assert_int_equal(tctx, r->in.unknown2, 0, "unknown 2");
+       torture_assert_int_equal(tctx, r->in.lookup_options, 0, "lookup_options");
+       torture_assert_int_equal(tctx, r->in.client_revision, 0, "client_revision");
        torture_assert_int_equal(tctx, *r->in.count, 0, "count");
        torture_assert_int_equal(tctx, r->in.sids->count, 0, "sids count");
        torture_assert(tctx, r->in.sids->sids == NULL, "sids sids");
index 2ed83d308cf35ec7dfab6d89cd2edf30872db093..68ef8e226d5f99353321188683045ab0946507e2 100644 (file)
@@ -147,11 +147,11 @@ static bool test_chkpath(struct smbcli_state *cli, struct torture_context *tctx)
        }
 
        ret &= test_path_ex(cli, tctx, BASEDIR, BASEDIR, NT_STATUS_OK, NT_STATUS_OK);
-       ret &= test_path_ex(cli, tctx, ((char *)BASEDIR) + 1, BASEDIR, NT_STATUS_OK, NT_STATUS_OK);
-       ret &= test_path_ex(cli, tctx, ((char *)BASEDIR"\\\\") + 1, BASEDIR, NT_STATUS_OK, NT_STATUS_OK);
-       ret &= test_path_ex(cli, tctx, ((char *)BASEDIR"\\foo\\..") + 1, BASEDIR, NT_STATUS_OK, NT_STATUS_OK);
-       ret &= test_path_ex(cli, tctx, ((char *)BASEDIR"\\f\\o\\o\\..\\..\\..") + 1, BASEDIR, NT_STATUS_OK, NT_STATUS_OK);
-       ret &= test_path_ex(cli, tctx, ((char *)BASEDIR"\\foo\\\\..\\\\") + 1, BASEDIR, NT_STATUS_OK, NT_STATUS_OK);
+       ret &= test_path_ex(cli, tctx, ((const char *)BASEDIR) + 1, BASEDIR, NT_STATUS_OK, NT_STATUS_OK);
+       ret &= test_path_ex(cli, tctx, ((const char *)BASEDIR"\\\\") + 1, BASEDIR, NT_STATUS_OK, NT_STATUS_OK);
+       ret &= test_path_ex(cli, tctx, ((const char *)BASEDIR"\\foo\\..") + 1, BASEDIR, NT_STATUS_OK, NT_STATUS_OK);
+       ret &= test_path_ex(cli, tctx, ((const char *)BASEDIR"\\f\\o\\o\\..\\..\\..") + 1, BASEDIR, NT_STATUS_OK, NT_STATUS_OK);
+       ret &= test_path_ex(cli, tctx, ((const char *)BASEDIR"\\foo\\\\..\\\\") + 1, BASEDIR, NT_STATUS_OK, NT_STATUS_OK);
        ret &= test_path_ex(cli, tctx, BASEDIR"\\", BASEDIR, NT_STATUS_OK, NT_STATUS_OK);
        ret &= test_path_ex(cli, tctx, BASEDIR"\\\\..\\"BASEDIR, BASEDIR, NT_STATUS_OK, NT_STATUS_OK);
        ret &= test_path_ex(cli, tctx, BASEDIR"\\\\\\", BASEDIR, NT_STATUS_OK, NT_STATUS_OK);
index d73ac1327e1b80c6556a7d7613846cb4b41688e5..7f1f5943e1c95fca65bf91c6c618d5145f74f3ae 100644 (file)
@@ -164,6 +164,7 @@ static bool test_fetchfile(struct smbcli_state *cli, struct torture_context *tct
        io2.in.filename = fname;
        io2.in.resolve_ctx = lp_resolve_context(tctx->lp_ctx);
        lp_smbcli_options(tctx->lp_ctx, &io2.in.options);
+       lp_smbcli_session_options(tctx->lp_ctx, &io2.in.session_options);
 
        printf("testing parallel fetchfile with %d ops\n", torture_numops);
 
@@ -358,7 +359,7 @@ static bool test_fsinfo(struct smbcli_state *cli, struct torture_context *tctx)
        c = talloc_array(tctx, struct composite_context *, torture_numops);
 
        for (i=0; i<torture_numops; i++) {
-               c[i] = smb_composite_fsinfo_send(cli->tree,&io1);
+               c[i] = smb_composite_fsinfo_send(cli->tree, &io1, lp_resolve_context(tctx->lp_ctx));
                c[i]->async.fn = loadfile_complete;
                c[i]->async.private_data = count;
        }
index 15e736fff51be6ae951eb995c1d00922ddcbeb6c..450ad0f2605b9eb66c53558084123e4ad7ade6b8 100644 (file)
@@ -81,6 +81,7 @@ static bool test_session(struct smbcli_state *cli, struct torture_context *tctx)
        const char *fname = BASEDIR "\\test.txt";
        uint8_t c = 1;
        int i;
+       struct smbcli_session_options options;
 
        printf("TESTING SESSION HANDLING\n");
 
@@ -89,7 +90,10 @@ static bool test_session(struct smbcli_state *cli, struct torture_context *tctx)
        }
 
        printf("create a second security context on the same transport\n");
-       session = smbcli_session_init(cli->transport, tctx, false);
+
+       lp_smbcli_session_options(tctx->lp_ctx, &options);
+
+       session = smbcli_session_init(cli->transport, tctx, false, options);
 
        setup.in.sesskey = cli->transport->negotiate.sesskey;
        setup.in.capabilities = cli->transport->negotiate.capabilities; /* ignored in secondary session setup, except by our libs, which care about the extended security bit */
@@ -103,7 +107,7 @@ static bool test_session(struct smbcli_state *cli, struct torture_context *tctx)
        session->vuid = setup.out.vuid;
 
        printf("create a third security context on the same transport, with vuid set\n");
-       session2 = smbcli_session_init(cli->transport, tctx, false);
+       session2 = smbcli_session_init(cli->transport, tctx, false, options);
 
        session2->vuid = session->vuid;
        setup.in.sesskey = cli->transport->negotiate.sesskey;
@@ -130,7 +134,7 @@ static bool test_session(struct smbcli_state *cli, struct torture_context *tctx)
 
        if (cli->transport->negotiate.capabilities & CAP_EXTENDED_SECURITY) {
                printf("create a fourth security context on the same transport, without extended security\n");
-               session3 = smbcli_session_init(cli->transport, tctx, false);
+               session3 = smbcli_session_init(cli->transport, tctx, false, options);
 
                session3->vuid = session->vuid;
                setup.in.sesskey = cli->transport->negotiate.sesskey;
@@ -144,7 +148,7 @@ static bool test_session(struct smbcli_state *cli, struct torture_context *tctx)
                CHECK_STATUS(status, NT_STATUS_LOGON_FAILURE);
 
                printf("create a fouth anonymous security context on the same transport, without extended security\n");
-               session4 = smbcli_session_init(cli->transport, tctx, false);
+               session4 = smbcli_session_init(cli->transport, tctx, false, options);
 
                session4->vuid = session->vuid;
                setup.in.sesskey = cli->transport->negotiate.sesskey;
@@ -230,7 +234,7 @@ static bool test_session(struct smbcli_state *cli, struct torture_context *tctx)
                
                setups[i].in.credentials = cmdline_credentials;
 
-               sessions[i] = smbcli_session_init(cli->transport, tctx, false);
+               sessions[i] = smbcli_session_init(cli->transport, tctx, false, options);
                composite_contexts[i] = smb_composite_sesssetup_send(sessions[i], &setups[i]);
 
        }
@@ -379,6 +383,7 @@ static bool test_tree_ulogoff(struct smbcli_state *cli, struct torture_context *
        const char *fname1 = BASEDIR "\\test1.txt";
        const char *fname2 = BASEDIR "\\test2.txt";
        uint8_t c = 1;
+       struct smbcli_session_options options;
 
        printf("TESTING TREE with ulogoff\n");
 
@@ -389,8 +394,10 @@ static bool test_tree_ulogoff(struct smbcli_state *cli, struct torture_context *
        share = torture_setting_string(tctx, "share", NULL);
        host  = torture_setting_string(tctx, "host", NULL);
 
+       lp_smbcli_session_options(tctx->lp_ctx, &options);
+
        printf("create the first new sessions\n");
-       session1 = smbcli_session_init(cli->transport, tctx, false);
+       session1 = smbcli_session_init(cli->transport, tctx, false, options);
        setup.in.sesskey = cli->transport->negotiate.sesskey;
        setup.in.capabilities = cli->transport->negotiate.capabilities;
        setup.in.workgroup = lp_workgroup(tctx->lp_ctx);
@@ -446,7 +453,7 @@ static bool test_tree_ulogoff(struct smbcli_state *cli, struct torture_context *
        CHECK_STATUS(status, NT_STATUS_OK);
 
        printf("create the second new sessions\n");
-       session2 = smbcli_session_init(cli->transport, tctx, false);
+       session2 = smbcli_session_init(cli->transport, tctx, false, options);
        setup.in.sesskey = cli->transport->negotiate.sesskey;
        setup.in.capabilities = cli->transport->negotiate.capabilities;
        setup.in.workgroup = lp_workgroup(tctx->lp_ctx);
@@ -634,6 +641,7 @@ static bool test_pid_2sess(struct smbcli_state *cli, struct torture_context *tct
        const char *fname = BASEDIR "\\test.txt";
        uint8_t c = 1;
        uint16_t vuid1, vuid2;
+       struct smbcli_session_options options;
 
        printf("TESTING PID HANDLING WITH 2 SESSIONS\n");
 
@@ -641,8 +649,10 @@ static bool test_pid_2sess(struct smbcli_state *cli, struct torture_context *tct
                return false;
        }
 
+       lp_smbcli_session_options(tctx->lp_ctx, &options);
+
        printf("create a second security context on the same transport\n");
-       session = smbcli_session_init(cli->transport, tctx, false);
+       session = smbcli_session_init(cli->transport, tctx, false, options);
 
        setup.in.sesskey = cli->transport->negotiate.sesskey;
        setup.in.capabilities = cli->transport->negotiate.capabilities; /* ignored in secondary session setup, except by our libs, which care about the extended security bit */
index cd8d60679520258a21ab96e28e5f63d53ca73e49..dbe071c9adf5cac7a709c12679ebe4777b7d7864 100644 (file)
@@ -456,11 +456,14 @@ static bool test_async(struct torture_context *tctx,
        const char *fname = BASEDIR "\\test.txt";
        time_t t;
        struct smbcli_request *req;
+       struct smbcli_session_options options;
 
        if (!torture_setup_dir(cli, BASEDIR)) {
                return false;
        }
 
+       lp_smbcli_session_options(tctx->lp_ctx, &options);
+
        printf("Testing LOCKING_ANDX_CANCEL_LOCK\n");
        io.generic.level = RAW_LOCK_LOCKX;
 
@@ -590,7 +593,7 @@ static bool test_async(struct torture_context *tctx,
        }
 
        printf("create a new sessions\n");
-       session = smbcli_session_init(cli->transport, tctx, false);
+       session = smbcli_session_init(cli->transport, tctx, false, options);
        setup.in.sesskey = cli->transport->negotiate.sesskey;
        setup.in.capabilities = cli->transport->negotiate.capabilities;
        setup.in.workgroup = lp_workgroup(tctx->lp_ctx);
index 21541d003b18eb9ad4ee13b496199eeb8881e8f7..26fad4235e9e793ae097d6fe1e248e43f047c7f5 100644 (file)
@@ -195,6 +195,7 @@ static void reopen_connection(struct event_context *ev, struct timed_event *te,
        io->in.fallback_to_anonymous = false;
        io->in.workgroup    = lp_workgroup(state->tctx->lp_ctx);
        lp_smbcli_options(state->tctx->lp_ctx, &io->in.options);
+       lp_smbcli_session_options(state->tctx->lp_ctx, &io->in.session_options);
 
        /* kill off the remnants of the old connection */
        talloc_free(state->tree);
index 25c91eb88bc9cce202e88c71d038334a900c1565..d7541b7c7132c689cab2876e1904b5f590c71b1c 100644 (file)
@@ -583,7 +583,9 @@ static bool test_notify_mask(struct smbcli_state *cli, struct torture_context *t
        notify.nttrans.in.buffer_size = 1000;
        notify.nttrans.in.recursive = true;
 
-#define NOTIFY_MASK_TEST(setup, op, cleanup, Action, expected, nchanges) \
+#define NOTIFY_MASK_TEST(test_name, setup, op, cleanup, Action, expected, nchanges) \
+       do { \
+       smbcli_getatr(cli->tree, test_name, NULL, NULL, NULL); \
        do { for (mask=i=0;i<32;i++) { \
                struct smbcli_request *req; \
                status = smb_raw_open(cli->tree, tctx, &io); \
@@ -640,24 +642,25 @@ static bool test_notify_mask(struct smbcli_state *cli, struct torture_context *t
                               mask, expected); \
                } \
        } \
-       } while (0)
+       } while (0); \
+       } while (0);
 
        printf("testing mkdir\n");
-       NOTIFY_MASK_TEST(;,
+       NOTIFY_MASK_TEST("testing mkdir",;,
                         smbcli_mkdir(cli->tree, BASEDIR "\\tname1");,
                         smbcli_rmdir(cli->tree, BASEDIR "\\tname1");,
                         NOTIFY_ACTION_ADDED,
                         FILE_NOTIFY_CHANGE_DIR_NAME, 1);
 
        printf("testing create file\n");
-       NOTIFY_MASK_TEST(;,
+       NOTIFY_MASK_TEST("testing create file",;,
                         smbcli_close(cli->tree, smbcli_open(cli->tree, BASEDIR "\\tname1", O_CREAT, 0));,
                         smbcli_unlink(cli->tree, BASEDIR "\\tname1");,
                         NOTIFY_ACTION_ADDED,
                         FILE_NOTIFY_CHANGE_FILE_NAME, 1);
 
        printf("testing unlink\n");
-       NOTIFY_MASK_TEST(
+       NOTIFY_MASK_TEST("testing unlink",
                         smbcli_close(cli->tree, smbcli_open(cli->tree, BASEDIR "\\tname1", O_CREAT, 0));,
                         smbcli_unlink(cli->tree, BASEDIR "\\tname1");,
                         ;,
@@ -665,7 +668,7 @@ static bool test_notify_mask(struct smbcli_state *cli, struct torture_context *t
                         FILE_NOTIFY_CHANGE_FILE_NAME, 1);
 
        printf("testing rmdir\n");
-       NOTIFY_MASK_TEST(
+       NOTIFY_MASK_TEST("testing rmdir",
                         smbcli_mkdir(cli->tree, BASEDIR "\\tname1");,
                         smbcli_rmdir(cli->tree, BASEDIR "\\tname1");,
                         ;,
@@ -673,7 +676,7 @@ static bool test_notify_mask(struct smbcli_state *cli, struct torture_context *t
                         FILE_NOTIFY_CHANGE_DIR_NAME, 1);
 
        printf("testing rename file\n");
-       NOTIFY_MASK_TEST(
+       NOTIFY_MASK_TEST("testing rename file",
                         smbcli_close(cli->tree, smbcli_open(cli->tree, BASEDIR "\\tname1", O_CREAT, 0));,
                         smbcli_rename(cli->tree, BASEDIR "\\tname1", BASEDIR "\\tname2");,
                         smbcli_unlink(cli->tree, BASEDIR "\\tname2");,
@@ -681,7 +684,7 @@ static bool test_notify_mask(struct smbcli_state *cli, struct torture_context *t
                         FILE_NOTIFY_CHANGE_FILE_NAME|FILE_NOTIFY_CHANGE_ATTRIBUTES|FILE_NOTIFY_CHANGE_CREATION, 2);
 
        printf("testing rename dir\n");
-       NOTIFY_MASK_TEST(
+       NOTIFY_MASK_TEST("testing rename dir",
                smbcli_mkdir(cli->tree, BASEDIR "\\tname1");,
                smbcli_rename(cli->tree, BASEDIR "\\tname1", BASEDIR "\\tname2");,
                smbcli_rmdir(cli->tree, BASEDIR "\\tname2");,
@@ -689,7 +692,7 @@ static bool test_notify_mask(struct smbcli_state *cli, struct torture_context *t
                FILE_NOTIFY_CHANGE_DIR_NAME, 2);
 
        printf("testing set path attribute\n");
-       NOTIFY_MASK_TEST(
+       NOTIFY_MASK_TEST("testing set path attribute",
                smbcli_close(cli->tree, smbcli_open(cli->tree, BASEDIR "\\tname1", O_CREAT, 0));,
                smbcli_setatr(cli->tree, BASEDIR "\\tname1", FILE_ATTRIBUTE_HIDDEN, 0);,
                smbcli_unlink(cli->tree, BASEDIR "\\tname1");,
@@ -697,7 +700,7 @@ static bool test_notify_mask(struct smbcli_state *cli, struct torture_context *t
                FILE_NOTIFY_CHANGE_ATTRIBUTES, 1);
 
        printf("testing set path write time\n");
-       NOTIFY_MASK_TEST(
+       NOTIFY_MASK_TEST("testing set path write time",
                smbcli_close(cli->tree, smbcli_open(cli->tree, BASEDIR "\\tname1", O_CREAT, 0));,
                smbcli_setatr(cli->tree, BASEDIR "\\tname1", FILE_ATTRIBUTE_NORMAL, 1000);,
                smbcli_unlink(cli->tree, BASEDIR "\\tname1");,
@@ -705,7 +708,7 @@ static bool test_notify_mask(struct smbcli_state *cli, struct torture_context *t
                FILE_NOTIFY_CHANGE_LAST_WRITE, 1);
 
        printf("testing set file attribute\n");
-       NOTIFY_MASK_TEST(
+       NOTIFY_MASK_TEST("testing set file attribute",
                fnum2 = create_complex_file(cli, tctx, BASEDIR "\\tname1");,
                smbcli_fsetatr(cli->tree, fnum2, FILE_ATTRIBUTE_HIDDEN, 0, 0, 0, 0);,
                (smbcli_close(cli->tree, fnum2), smbcli_unlink(cli->tree, BASEDIR "\\tname1"));,
@@ -718,7 +721,7 @@ static bool test_notify_mask(struct smbcli_state *cli, struct torture_context *t
        }
        else {
                printf("testing set file create time\n");
-               NOTIFY_MASK_TEST(
+               NOTIFY_MASK_TEST("testing set file create time",
                        fnum2 = create_complex_file(cli, tctx,
                                                    BASEDIR "\\tname1");,
                        smbcli_fsetatr(cli->tree, fnum2, 0, t, 0, 0, 0);,
@@ -729,7 +732,7 @@ static bool test_notify_mask(struct smbcli_state *cli, struct torture_context *t
        }
 
        printf("testing set file access time\n");
-       NOTIFY_MASK_TEST(
+       NOTIFY_MASK_TEST("testing set file access time",
                fnum2 = create_complex_file(cli, tctx, BASEDIR "\\tname1");,
                smbcli_fsetatr(cli->tree, fnum2, 0, 0, t, 0, 0);,
                (smbcli_close(cli->tree, fnum2), smbcli_unlink(cli->tree, BASEDIR "\\tname1"));,
@@ -737,7 +740,7 @@ static bool test_notify_mask(struct smbcli_state *cli, struct torture_context *t
                FILE_NOTIFY_CHANGE_LAST_ACCESS, 1);
 
        printf("testing set file write time\n");
-       NOTIFY_MASK_TEST(
+       NOTIFY_MASK_TEST("testing set file write time",
                fnum2 = create_complex_file(cli, tctx, BASEDIR "\\tname1");,
                smbcli_fsetatr(cli->tree, fnum2, 0, 0, 0, t, 0);,
                (smbcli_close(cli->tree, fnum2), smbcli_unlink(cli->tree, BASEDIR "\\tname1"));,
@@ -745,7 +748,7 @@ static bool test_notify_mask(struct smbcli_state *cli, struct torture_context *t
                FILE_NOTIFY_CHANGE_LAST_WRITE, 1);
 
        printf("testing set file change time\n");
-       NOTIFY_MASK_TEST(
+       NOTIFY_MASK_TEST("testing set file change time",
                fnum2 = create_complex_file(cli, tctx, BASEDIR "\\tname1");,
                smbcli_fsetatr(cli->tree, fnum2, 0, 0, 0, 0, t);,
                (smbcli_close(cli->tree, fnum2), smbcli_unlink(cli->tree, BASEDIR "\\tname1"));,
@@ -754,7 +757,7 @@ static bool test_notify_mask(struct smbcli_state *cli, struct torture_context *t
 
 
        printf("testing write\n");
-       NOTIFY_MASK_TEST(
+       NOTIFY_MASK_TEST("testing write",
                fnum2 = create_complex_file(cli, tctx, BASEDIR "\\tname1");,
                smbcli_write(cli->tree, fnum2, 1, &c, 10000, 1);,
                (smbcli_close(cli->tree, fnum2), smbcli_unlink(cli->tree, BASEDIR "\\tname1"));,
@@ -762,7 +765,7 @@ static bool test_notify_mask(struct smbcli_state *cli, struct torture_context *t
                0, 1);
 
        printf("testing truncate\n");
-       NOTIFY_MASK_TEST(
+       NOTIFY_MASK_TEST("testing truncate",
                fnum2 = create_complex_file(cli, tctx, BASEDIR "\\tname1");,
                smbcli_ftruncate(cli->tree, fnum2, 10000);,
                (smbcli_close(cli->tree, fnum2), smbcli_unlink(cli->tree, BASEDIR "\\tname1"));,
index f3494ea3d09f62d1321fa263a14600b175e25fe0..dd5ef0d0b9188d6bb846362658df2852c7529589 100644 (file)
@@ -1545,6 +1545,64 @@ static bool test_raw_open_multi(struct torture_context *tctx)
        return ret;
 }
 
+/*
+  test opening for delete on a read-only attribute file.
+*/
+static bool test_open_for_delete(struct smbcli_state *cli, struct torture_context *tctx)
+{
+       union smb_open io;
+       union smb_fileinfo finfo;
+       const char *fname = BASEDIR "\\torture_open_for_delete.txt";
+       NTSTATUS status;
+       int fnum = -1;
+       bool ret = true;
+
+       printf("Checking RAW_NTCREATEX for delete on a readonly file.\n");
+
+       /* reasonable default parameters */
+       io.generic.level = RAW_OPEN_NTCREATEX;
+       io.ntcreatex.in.flags = NTCREATEX_FLAGS_EXTENDED;
+       io.ntcreatex.in.root_fid = 0;
+       io.ntcreatex.in.alloc_size = 0;
+       io.ntcreatex.in.access_mask = SEC_RIGHTS_FILE_ALL;
+       io.ntcreatex.in.file_attr = FILE_ATTRIBUTE_READONLY;
+       io.ntcreatex.in.share_access = NTCREATEX_SHARE_ACCESS_NONE;
+       io.ntcreatex.in.open_disposition = NTCREATEX_DISP_CREATE;
+       io.ntcreatex.in.create_options = 0;
+       io.ntcreatex.in.impersonation = NTCREATEX_IMPERSONATION_ANONYMOUS;
+       io.ntcreatex.in.security_flags = 0;
+       io.ntcreatex.in.fname = fname;
+
+       /* Create the readonly file. */
+
+       status = smb_raw_open(cli->tree, tctx, &io);
+       CHECK_STATUS(status, NT_STATUS_OK);
+       fnum = io.ntcreatex.out.file.fnum;
+
+       CHECK_VAL(io.ntcreatex.out.oplock_level, 0);
+       io.ntcreatex.in.create_options = 0;
+       CHECK_VAL(io.ntcreatex.out.create_action, NTCREATEX_ACTION_CREATED);
+       CHECK_ALL_INFO(io.ntcreatex.out.attrib, attrib);
+       smbcli_close(cli->tree, fnum);
+
+       /* Now try and open for delete only - should succeed. */
+       io.ntcreatex.in.access_mask = SEC_STD_DELETE;
+       io.ntcreatex.in.file_attr = 0;
+       io.ntcreatex.in.share_access = NTCREATEX_SHARE_ACCESS_READ | NTCREATEX_SHARE_ACCESS_WRITE | NTCREATEX_SHARE_ACCESS_DELETE;
+       io.ntcreatex.in.open_disposition = NTCREATEX_DISP_OPEN;
+       status = smb_raw_open(cli->tree, tctx, &io);
+       CHECK_STATUS(status, NT_STATUS_OK);
+
+       smbcli_unlink(cli->tree, fname);
+
+done:
+       smbcli_close(cli->tree, fnum);
+       smbcli_unlink(cli->tree, fname);
+
+       return ret;
+}
+
+
 /* basic testing of all RAW_OPEN_* calls 
 */
 bool torture_raw_open(struct torture_context *torture, struct smbcli_state *cli)
@@ -1567,6 +1625,7 @@ bool torture_raw_open(struct torture_context *torture, struct smbcli_state *cli)
        ret &= test_ctemp(cli, torture);
        ret &= test_chained(cli, torture);
        ret &= test_no_leading_slash(cli, torture);
+       ret &= test_open_for_delete(cli, torture);
 
        smb_raw_exit(cli->session);
        smbcli_deltree(cli->tree, BASEDIR);
index 26b862c33f1d1255387ab0fae2e27049e6dcee75..ec94637445a3b0f73a3488342ff4be7b0c1237ce 100644 (file)
@@ -137,6 +137,7 @@ static void reopen_connection(struct event_context *ev, struct timed_event *te,
        io->in.fallback_to_anonymous = false;
        io->in.workgroup    = lp_workgroup(state->tctx->lp_ctx);
        lp_smbcli_options(state->tctx->lp_ctx, &io->in.options);
+       lp_smbcli_session_options(state->tctx->lp_ctx, &io->in.session_options);
 
        /* kill off the remnants of the old connection */
        talloc_free(state->tree);
index fd8d292980aa48c13eaf735440b1c7bfa31e2560..7e964b4d426ed66f83e1c445233855972da93d6d 100644 (file)
@@ -175,10 +175,11 @@ static bool open_connection_no_level2_oplocks(struct torture_context *tctx,
                                              struct smbcli_state **c)
 {
        NTSTATUS status;
-
        struct smbcli_options options;
+       struct smbcli_session_options session_options;
 
        lp_smbcli_options(tctx->lp_ctx, &options);
+       lp_smbcli_session_options(tctx->lp_ctx, &session_options);
 
        options.use_level2_oplocks = false;
 
@@ -188,7 +189,7 @@ static bool open_connection_no_level2_oplocks(struct torture_context *tctx,
                                        torture_setting_string(tctx, "share", NULL),
                                        NULL, cmdline_credentials,
                                        lp_resolve_context(tctx->lp_ctx),
-                                       tctx->ev, &options);
+                                       tctx->ev, &options, &session_options);
        if (!NT_STATUS_IS_OK(status)) {
                printf("Failed to open connection - %s\n", nt_errstr(status));
                return false;
index 6f0ba0d617e62ce2359563005a3a2fb752577527..66ef2ae2dde8e761a7459b7d635a1995dfc3cf42 100644 (file)
@@ -69,8 +69,10 @@ static int fork_tcon_client(struct torture_context *tctx,
        struct timeval end;
        struct timeval now;
        struct smbcli_options options;
+       struct smbcli_session_options session_options;
 
        lp_smbcli_options(tctx->lp_ctx, &options);
+       lp_smbcli_session_options(tctx->lp_ctx, &session_options);
 
        child = fork();
        if (child == -1) {
@@ -100,7 +102,7 @@ static int fork_tcon_client(struct torture_context *tctx,
                                host, lp_smb_ports(tctx->lp_ctx), share,
                                NULL, cmdline_credentials,
                                lp_resolve_context(tctx->lp_ctx),
-                               tctx->ev, &options);
+                               tctx->ev, &options, &session_options);
 
                if (!NT_STATUS_IS_OK(status)) {
                        printf("failed to connect to //%s/%s: %s\n",
index fbda69df57ec297fffbe2c55dfe313e911ab9c88..a9a614953d674a5b1583e867215b760b24150d50 100644 (file)
@@ -39,6 +39,7 @@ static bool test_DsCrackNamesMatrix(struct dcerpc_pipe *p, TALLOC_CTX *mem_ctx,
        bool ret = true;
        struct drsuapi_DsCrackNames r;
        enum drsuapi_DsNameFormat formats[] = {
+               DRSUAPI_DS_NAME_FORMAT_UNKNOWN,
                DRSUAPI_DS_NAME_FORMAT_FQDN_1779,
                DRSUAPI_DS_NAME_FORMAT_NT4_ACCOUNT,
                DRSUAPI_DS_NAME_FORMAT_DISPLAY,
index df16c860cbf6dc2bf744150eed322218a3099cfc..41bb168619138e8d2289247969f670f11c15f1aa 100644 (file)
@@ -310,14 +310,14 @@ static bool test_GetInfo(struct torture_context *tctx, struct DsSyncTest *ctx)
                ctx->site_name = talloc_asprintf(ctx, "%s", "Default-First-Site-Name");
                printf("cldap_netlogon() returned %s. Defaulting to Site-Name: %s\n", errstr, ctx->site_name);          
        } else {
-               ctx->site_name = talloc_steal(ctx, search.out.netlogon.nt5_ex.client_site);
+               ctx->site_name = talloc_steal(ctx, search.out.netlogon.data.nt5_ex.client_site);
                printf("cldap_netlogon() returned Client Site-Name: %s.\n",ctx->site_name);
-               printf("cldap_netlogon() returned Server Site-Name: %s.\n",search.out.netlogon.nt5_ex.server_site);
+               printf("cldap_netlogon() returned Server Site-Name: %s.\n",search.out.netlogon.data.nt5_ex.server_site);
        }
 
        if (!ctx->domain_dn) {
                struct ldb_context *ldb = ldb_init(ctx, tctx->ev);
-               struct ldb_dn *dn = samdb_dns_domain_to_dn(ldb, ctx, search.out.netlogon.nt5_ex.dns_domain);
+               struct ldb_dn *dn = samdb_dns_domain_to_dn(ldb, ctx, search.out.netlogon.data.nt5_ex.dns_domain);
                ctx->domain_dn = ldb_dn_alloc_linearized(ctx, dn);
                talloc_free(dn);
                talloc_free(ldb);
index 77da32d5725ab6a08a63d9cc11854c0bda78f14c..ee0c05360fcd47af039a12c65450edc2c04a0044 100644 (file)
@@ -19,6 +19,7 @@ bool torture_rpc_join(struct torture_context *torture)
        struct smbcli_state *cli;
        const char *host = torture_setting_string(torture, "host", NULL);
        struct smbcli_options options;
+       struct smbcli_session_options session_options;
 
        /* Join domain as a member server. */
        tj = torture_join_domain(torture,
@@ -33,13 +34,14 @@ bool torture_rpc_join(struct torture_context *torture)
        }
 
        lp_smbcli_options(torture->lp_ctx, &options);
+       lp_smbcli_session_options(torture->lp_ctx, &session_options);
 
        status = smbcli_full_connection(tj, &cli, host,
                                        lp_smb_ports(torture->lp_ctx),
                                        "IPC$", NULL,
                                        machine_account,
                                        lp_resolve_context(torture->lp_ctx),
-                                       torture->ev, &options);
+                                       torture->ev, &options, &session_options);
        if (!NT_STATUS_IS_OK(status)) {
                DEBUG(0, ("%s failed to connect to IPC$ with workstation credentials\n",
                          TORTURE_NETBIOS_NAME));
@@ -65,7 +67,7 @@ bool torture_rpc_join(struct torture_context *torture)
                                        "IPC$", NULL,
                                        machine_account,
                                        lp_resolve_context(torture->lp_ctx),
-                                       torture->ev, &options);
+                                       torture->ev, &options, &session_options);
        if (!NT_STATUS_IS_OK(status)) {
                DEBUG(0, ("%s failed to connect to IPC$ with workstation credentials\n",
                          TORTURE_NETBIOS_NAME));
index 69bf33352b843e3aae74be3bb72fdfe7f980a38b..245ed1e41bb197ed7d993fdffe3727fd9c721a3b 100644 (file)
@@ -222,12 +222,13 @@ static bool test_LookupNames_bogus(struct dcerpc_pipe *p,
        NTSTATUS status;
        int i;
 
-       struct lsa_TranslatedName name;
+       struct lsa_TranslatedName name[2];
        struct lsa_TransNameArray tnames;
 
-       tnames.names = &name;
-       tnames.count = 1;
-       name.name.string = "NT AUTHORITY\\BOGUS";
+       tnames.names = name;
+       tnames.count = 2;
+       name[0].name.string = "NT AUTHORITY\\BOGUS";
+       name[1].name.string = NULL;
 
        printf("\nTesting LookupNames with bogus names\n");
 
@@ -337,8 +338,8 @@ static bool test_LookupNames2(struct dcerpc_pipe *p,
        r.in.sids = &sids;
        r.in.level = 1;
        r.in.count = &count;
-       r.in.unknown1 = 0;
-       r.in.unknown2 = 0;
+       r.in.lookup_options = 0;
+       r.in.client_revision = 0;
        r.out.count = &count;
        r.out.sids = &sids;
 
@@ -382,8 +383,8 @@ static bool test_LookupNames3(struct dcerpc_pipe *p,
        r.in.sids = &sids;
        r.in.level = 1;
        r.in.count = &count;
-       r.in.unknown1 = 0;
-       r.in.unknown2 = 0;
+       r.in.lookup_options = 0;
+       r.in.client_revision = 0;
        r.out.count = &count;
        r.out.sids = &sids;
 
@@ -424,8 +425,8 @@ static bool test_LookupNames4(struct dcerpc_pipe *p,
        r.in.sids = &sids;
        r.in.level = 1;
        r.in.count = &count;
-       r.in.unknown1 = 0;
-       r.in.unknown2 = 0;
+       r.in.lookup_options = 0;
+       r.in.client_revision = 0;
        r.out.count = &count;
        r.out.sids = &sids;
 
@@ -1898,7 +1899,11 @@ static bool test_EnumTrustDom(struct dcerpc_pipe *p,
                
                /* NO_MORE_ENTRIES is allowed */
                if (NT_STATUS_EQUAL(enum_status, NT_STATUS_NO_MORE_ENTRIES)) {
-                       return true;
+                       if (domains.count == 0) {
+                               return true;
+                       }
+                       printf("EnumTrustDom failed - should have returned 0 trusted domains with 'NT_STATUS_NO_MORE_ENTRIES'\n");
+                       return false;
                } else if (NT_STATUS_EQUAL(enum_status, STATUS_MORE_ENTRIES)) {
                        /* Windows 2003 gets this off by one on the first run */
                        if (r.out.domains->count < 3 || r.out.domains->count > 4) {
@@ -1949,7 +1954,11 @@ static bool test_EnumTrustDom(struct dcerpc_pipe *p,
                
                /* NO_MORE_ENTRIES is allowed */
                if (NT_STATUS_EQUAL(enum_status, NT_STATUS_NO_MORE_ENTRIES)) {
-                       return true;
+                       if (domains_ex.count == 0) {
+                               return true;
+                       }
+                       printf("EnumTrustDomainsEx failed - should have returned 0 trusted domains with 'NT_STATUS_NO_MORE_ENTRIES'\n");
+                       return false;
                } else if (NT_STATUS_EQUAL(enum_status, STATUS_MORE_ENTRIES)) {
                        /* Windows 2003 gets this off by one on the first run */
                        if (r_ex.out.domains->count < 3 || r_ex.out.domains->count > 4) {
@@ -2077,7 +2086,7 @@ static bool test_CreateTrustedDomainEx2(struct dcerpc_pipe *p,
        struct lsa_CreateTrustedDomainEx2 r;
        struct lsa_TrustDomainInfoInfoEx trustinfo;
        struct lsa_TrustDomainInfoAuthInfoInternal authinfo;
-       struct trustAuthInAndOutBlob auth_struct;
+       struct trustDomainPasswords auth_struct;
        DATA_BLOB auth_blob;
        struct dom_sid *domsid[12];
        struct policy_handle trustdom_handle[12];
@@ -2114,7 +2123,7 @@ static bool test_CreateTrustedDomainEx2(struct dcerpc_pipe *p,
 
                /* Try different trust types too */
 
-               /* 1 == downleven (NT4), 2 == uplevel (ADS), 3 == MIT (kerberos but not AD) */
+               /* 1 == downlevel (NT4), 2 == uplevel (ADS), 3 == MIT (kerberos but not AD) */
                trustinfo.trust_type = (((i / 3) + 1) % 3) + 1;
 
                trustinfo.trust_attributes = LSA_TRUST_ATTRIBUTE_USES_RC4_ENCRYPTION;
@@ -2125,9 +2134,9 @@ static bool test_CreateTrustedDomainEx2(struct dcerpc_pipe *p,
                auth_struct.incoming.count = 0;
 
                ndr_err = ndr_push_struct_blob(&auth_blob, mem_ctx, lp_iconv_convenience(tctx->lp_ctx), &auth_struct,
-                                              (ndr_push_flags_fn_t)ndr_push_trustAuthInAndOutBlob);
+                                              (ndr_push_flags_fn_t)ndr_push_trustDomainPasswords);
                if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
-                       printf("ndr_push_struct_blob of trustAuthInAndOutBlob structure failed");
+                       printf("ndr_push_struct_blob of trustDomainPasswords structure failed");
                        ret = false;
                }
 
@@ -2159,6 +2168,7 @@ static bool test_CreateTrustedDomainEx2(struct dcerpc_pipe *p,
                                printf("QueryTrustedDomainInfo level 1 failed - %s\n", nt_errstr(status));
                                ret = false;
                        } else if (!q.out.info) {
+                               printf("QueryTrustedDomainInfo level 1 failed to return an info pointer\n");
                                ret = false;
                        } else {
                                if (strcmp(q.out.info->info_ex.netbios_name.string, trustinfo.netbios_name.string) != 0) {
@@ -2187,11 +2197,13 @@ static bool test_CreateTrustedDomainEx2(struct dcerpc_pipe *p,
 
        /* now that we have some domains to look over, we can test the enum calls */
        if (!test_EnumTrustDom(p, mem_ctx, handle)) {
+               printf("test_EnumTrustDom failed\n");
                ret = false;
        }
        
        for (i=0; i<12; i++) {
                if (!test_DeleteTrustedDomainBySid(p, mem_ctx, handle, domsid[i])) {
+                       printf("test_DeleteTrustedDomainBySid failed\n");
                        ret = false;
                }
        }
@@ -2242,7 +2254,7 @@ static bool test_QueryInfoPolicy(struct dcerpc_pipe *p,
        bool ret = true;
        printf("\nTesting QueryInfoPolicy\n");
 
-       for (i=1;i<13;i++) {
+       for (i=1;i<=13;i++) {
                r.in.handle = handle;
                r.in.level = i;
 
@@ -2261,7 +2273,14 @@ static bool test_QueryInfoPolicy(struct dcerpc_pipe *p,
                        break;
                case LSA_POLICY_INFO_DOMAIN:
                case LSA_POLICY_INFO_ACCOUNT_DOMAIN:
+               case LSA_POLICY_INFO_DNS_INT:
                case LSA_POLICY_INFO_DNS:
+               case LSA_POLICY_INFO_REPLICA:
+               case LSA_POLICY_INFO_QUOTA:
+               case LSA_POLICY_INFO_ROLE:
+               case LSA_POLICY_INFO_AUDIT_LOG:
+               case LSA_POLICY_INFO_AUDIT_EVENTS:
+               case LSA_POLICY_INFO_PD:
                        if (!NT_STATUS_IS_OK(status)) {
                                printf("QueryInfoPolicy failed - %s\n", nt_errstr(status));
                                ret = false;
@@ -2351,7 +2370,14 @@ static bool test_QueryInfoPolicy2(struct dcerpc_pipe *p,
                        break;
                case LSA_POLICY_INFO_DOMAIN:
                case LSA_POLICY_INFO_ACCOUNT_DOMAIN:
+               case LSA_POLICY_INFO_DNS_INT:
                case LSA_POLICY_INFO_DNS:
+               case LSA_POLICY_INFO_REPLICA:
+               case LSA_POLICY_INFO_QUOTA:
+               case LSA_POLICY_INFO_ROLE:
+               case LSA_POLICY_INFO_AUDIT_LOG:
+               case LSA_POLICY_INFO_AUDIT_EVENTS:
+               case LSA_POLICY_INFO_PD:
                        if (!NT_STATUS_IS_OK(status)) {
                                printf("QueryInfoPolicy2 failed - %s\n", nt_errstr(status));
                                ret = false;
@@ -2457,7 +2483,6 @@ bool torture_rpc_lsa(struct torture_context *tctx)
                if (!join) {
                        ret = false;
                }
-
                if (!test_LookupNames_wellknown(p, tctx, handle)) {
                        ret = false;
                }               
@@ -2481,7 +2506,6 @@ bool torture_rpc_lsa(struct torture_context *tctx)
                if (!test_CreateSecret(p, tctx, handle)) {
                        ret = false;
                }
-               
                if (!test_CreateTrustedDomain(p, tctx, handle)) {
                        ret = false;
                }
index 2522062696b614334b474a36fe22fe2c74f07fd4..3d4c594d05aa910985a4904e56c613d2d551945b 100644 (file)
@@ -1397,7 +1397,14 @@ static bool test_GetDomainInfo(struct torture_context *tctx,
        q1.blob2.data = NULL;
        q1.product.string = "product string";
 
-       torture_comment(tctx, "Testing netr_uogonGetDomainInfo\n");
+       torture_comment(tctx, "Testing netr_LogonGetDomainInfo\n");
+
+       status = dcerpc_netr_LogonGetDomainInfo(p, tctx, &r);
+       torture_assert_ntstatus_ok(tctx, status, "netr_LogonGetDomainInfo");
+       torture_assert(tctx, creds_client_check(creds, &a.cred), "Credential chaining failed");
+
+       torture_comment(tctx, "Testing netr_LogonGetDomainInfo 2nd call\n");
+       creds_client_authenticator(creds, &a);
 
        status = dcerpc_netr_LogonGetDomainInfo(p, tctx, &r);
        torture_assert_ntstatus_ok(tctx, status, "netr_LogonGetDomainInfo");
@@ -1581,6 +1588,7 @@ struct torture_suite *torture_rpc_netlogon(TALLOC_CTX *mem_ctx)
 
        tcase = torture_suite_add_machine_rpc_iface_tcase(suite, "netlogon", 
                                                  &ndr_table_netlogon, TEST_MACHINE_NAME);
+
        torture_rpc_tcase_add_test(tcase, "LogonUasLogon", test_LogonUasLogon);
        torture_rpc_tcase_add_test(tcase, "LogonUasLogoff", test_LogonUasLogoff);
        torture_rpc_tcase_add_test_creds(tcase, "SamLogon", test_SamLogon);
diff --git a/source4/torture/rpc/object_uuid.c b/source4/torture/rpc/object_uuid.c
new file mode 100644 (file)
index 0000000..5a77bd1
--- /dev/null
@@ -0,0 +1,87 @@
+/*
+   Unix SMB/CIFS implementation.
+
+   test suite for behaviour of object uuids in rpc requests
+
+   Copyright (C) Stefan Metzmacher 2008
+
+   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 "torture/torture.h"
+#include "librpc/gen_ndr/ndr_dssetup.h"
+#include "librpc/gen_ndr/ndr_dssetup_c.h"
+#include "librpc/gen_ndr/ndr_lsa.h"
+#include "librpc/gen_ndr/ndr_lsa_c.h"
+#include "torture/rpc/rpc.h"
+
+/*
+  this tests the send object uuids in the dcerpc request
+*/
+
+static bool test_random_uuid(struct torture_context *torture)
+{
+       NTSTATUS status;
+       struct dcerpc_pipe *p1, *p2;
+       struct rpc_request *req;
+       struct GUID uuid;
+       struct dssetup_DsRoleGetPrimaryDomainInformation r1;
+       struct lsa_GetUserName r2;
+       struct lsa_StringPointer authority_name_p;
+
+       torture_comment(torture, "RPC-OBJECTUUID-RANDOM\n");
+
+       status = torture_rpc_connection(torture, &p1, &ndr_table_dssetup);
+       torture_assert_ntstatus_ok(torture, status, "opening dsetup pipe1");
+
+       status = torture_rpc_connection(torture, &p2, &ndr_table_lsarpc);
+       torture_assert_ntstatus_ok(torture, status, "opening lsa pipe1");
+
+       uuid = GUID_random();
+
+       r1.in.level = DS_ROLE_BASIC_INFORMATION;
+       req = dcerpc_ndr_request_send(p1, &uuid,
+                                     &ndr_table_dssetup,
+                                     NDR_DSSETUP_DSROLEGETPRIMARYDOMAININFORMATION,
+                                     torture, &r1);
+       status = dcerpc_ndr_request_recv(req);
+       torture_assert_ntstatus_ok(torture, status, "DsRoleGetPrimaryDomainInformation failed");
+       torture_assert_werr_ok(torture, r1.out.result, "DsRoleGetPrimaryDomainInformation failed");
+
+       uuid = GUID_random();
+
+       r2.in.system_name = "\\";
+       r2.in.account_name = NULL;
+       r2.in.authority_name = &authority_name_p;
+       authority_name_p.string = NULL;
+
+       req = dcerpc_ndr_request_send(p2, &uuid,
+                                     &ndr_table_lsarpc,
+                                     NDR_LSA_GETUSERNAME,
+                                     torture, &r2);
+       status = dcerpc_ndr_request_recv(req);
+       torture_assert_ntstatus_ok(torture, status, "lsaClose failed");
+       torture_assert_ntstatus_ok(torture, r2.out.result, "lsaClose failed");
+
+       return true;
+}
+
+struct torture_suite *torture_rpc_object_uuid(TALLOC_CTX *mem_ctx)
+{
+       struct torture_suite *suite;
+       suite = torture_suite_create(mem_ctx, "OBJECTUUID");
+       torture_suite_add_simple_test(suite, "random-uuid", test_random_uuid);
+       return suite;
+}
index 85f7bde16c60e3f7a7146308d8e9a79d95920a96..c35f93e3f90571a0ee1d661b0468cc62f93ecb78 100644 (file)
@@ -387,6 +387,7 @@ NTSTATUS torture_rpc_init(void)
        torture_suite_add_suite(suite, torture_rpc_atsvc(suite));
        torture_suite_add_suite(suite, torture_rpc_wkssvc(suite));
        torture_suite_add_suite(suite, torture_rpc_handles(suite));
+       torture_suite_add_suite(suite, torture_rpc_object_uuid(suite));
        torture_suite_add_suite(suite, torture_rpc_winreg(suite));
        torture_suite_add_simple_test(suite, "SPOOLSS", torture_rpc_spoolss);
        torture_suite_add_suite(suite, torture_rpc_spoolss_notify(suite));
index 3bbf6cf22309d0a0445920c50c8c29c548fc4c00..260c1cc1499bc6baeb74f19b8c940352e00e0d49 100644 (file)
@@ -74,6 +74,7 @@ bool torture_bind_authcontext(struct torture_context *torture)
        struct cli_credentials *anon_creds;
        struct smb_composite_sesssetup setup;
        struct smbcli_options options;
+       struct smbcli_session_options session_options;
 
        mem_ctx = talloc_init("torture_bind_authcontext");
 
@@ -83,13 +84,14 @@ bool torture_bind_authcontext(struct torture_context *torture)
        }
 
        lp_smbcli_options(torture->lp_ctx, &options);
+       lp_smbcli_session_options(torture->lp_ctx, &session_options);
 
        status = smbcli_full_connection(mem_ctx, &cli,
                                        torture_setting_string(torture, "host", NULL),
                                        lp_smb_ports(torture->lp_ctx),
                                        "IPC$", NULL, cmdline_credentials,
                                        lp_resolve_context(torture->lp_ctx),
-                                       torture->ev, &options);
+                                       torture->ev, &options, &session_options);
        if (!NT_STATUS_IS_OK(status)) {
                d_printf("smbcli_full_connection failed: %s\n",
                         nt_errstr(status));
@@ -142,7 +144,7 @@ bool torture_bind_authcontext(struct torture_context *torture)
                goto done;
        }
 
-       session2 = smbcli_session_init(cli->transport, mem_ctx, false);
+       session2 = smbcli_session_init(cli->transport, mem_ctx, false, session_options);
        if (session2 == NULL) {
                d_printf("smbcli_session_init failed\n");
                goto done;
@@ -288,6 +290,7 @@ bool torture_bind_samba3(struct torture_context *torture)
        bool ret = false;
        struct smbcli_state *cli;
        struct smbcli_options options;
+       struct smbcli_session_options session_options;
 
        mem_ctx = talloc_init("torture_bind_authcontext");
 
@@ -297,13 +300,14 @@ bool torture_bind_samba3(struct torture_context *torture)
        }
 
        lp_smbcli_options(torture->lp_ctx, &options);
+       lp_smbcli_session_options(torture->lp_ctx, &session_options);
 
        status = smbcli_full_connection(mem_ctx, &cli,
                                        torture_setting_string(torture, "host", NULL),
                                        lp_smb_ports(torture->lp_ctx),
                                        "IPC$", NULL, cmdline_credentials,
                                        lp_resolve_context(torture->lp_ctx),
-                                       torture->ev, &options);
+                                       torture->ev, &options, &session_options);
        if (!NT_STATUS_IS_OK(status)) {
                d_printf("smbcli_full_connection failed: %s\n",
                         nt_errstr(status));
@@ -1195,6 +1199,7 @@ bool torture_netlogon_samba3(struct torture_context *torture)
        const char *wks_name;
        int i;
        struct smbcli_options options;
+       struct smbcli_session_options session_options;
 
        wks_name = torture_setting_string(torture, "wksname", NULL);
        if (wks_name == NULL) {
@@ -1214,13 +1219,14 @@ bool torture_netlogon_samba3(struct torture_context *torture)
        }
 
        lp_smbcli_options(torture->lp_ctx, &options);
+       lp_smbcli_session_options(torture->lp_ctx, &session_options);
 
        status = smbcli_full_connection(mem_ctx, &cli,
                                        torture_setting_string(torture, "host", NULL),
                                        lp_smb_ports(torture->lp_ctx),
                                        "IPC$", NULL, anon_creds, 
                                        lp_resolve_context(torture->lp_ctx),
-                                       torture->ev, &options);
+                                       torture->ev, &options, &session_options);
        if (!NT_STATUS_IS_OK(status)) {
                d_printf("smbcli_full_connection failed: %s\n",
                         nt_errstr(status));
@@ -1299,15 +1305,17 @@ static bool test_join3(struct torture_context *tctx,
        struct smbcli_state *cli;
        struct cli_credentials *wks_creds;
        struct smbcli_options options;
+       struct smbcli_session_options session_options;
 
        lp_smbcli_options(tctx->lp_ctx, &options);
+       lp_smbcli_session_options(tctx->lp_ctx, &session_options);
 
        status = smbcli_full_connection(tctx, &cli,
                                        torture_setting_string(tctx, "host", NULL),
                                        lp_smb_ports(tctx->lp_ctx),
                                        "IPC$", NULL, smb_creds, 
                                        lp_resolve_context(tctx->lp_ctx),
-                                       tctx->ev, &options);
+                                       tctx->ev, &options, &session_options);
        if (!NT_STATUS_IS_OK(status)) {
                d_printf("smbcli_full_connection failed: %s\n",
                         nt_errstr(status));
@@ -1670,19 +1678,21 @@ bool torture_samba3_rpc_getusername(struct torture_context *torture)
        struct cli_credentials *user_creds;
        char *domain_name;
        struct smbcli_options options;
+       struct smbcli_session_options session_options;
 
        if (!(mem_ctx = talloc_new(torture))) {
                return false;
        }
 
        lp_smbcli_options(torture->lp_ctx, &options);
+       lp_smbcli_session_options(torture->lp_ctx, &session_options);
 
        status = smbcli_full_connection(
                mem_ctx, &cli, torture_setting_string(torture, "host", NULL),
                lp_smb_ports(torture->lp_ctx),
                "IPC$", NULL, cmdline_credentials, 
                lp_resolve_context(torture->lp_ctx),
-               torture->ev, &options);
+               torture->ev, &options, &session_options);
        if (!NT_STATUS_IS_OK(status)) {
                d_printf("(%s) smbcli_full_connection failed: %s\n",
                         __location__, nt_errstr(status));
@@ -1709,7 +1719,7 @@ bool torture_samba3_rpc_getusername(struct torture_context *torture)
                lp_smb_ports(torture->lp_ctx),
                "IPC$", NULL, anon_creds, 
                lp_resolve_context(torture->lp_ctx),
-               torture->ev, &options);
+               torture->ev, &options, &session_options);
        if (!NT_STATUS_IS_OK(status)) {
                d_printf("(%s) anon smbcli_full_connection failed: %s\n",
                         __location__, nt_errstr(status));
@@ -1762,7 +1772,7 @@ bool torture_samba3_rpc_getusername(struct torture_context *torture)
                struct smb_composite_sesssetup setup;
                struct smbcli_tree *tree;
 
-               session2 = smbcli_session_init(cli->transport, mem_ctx, false);
+               session2 = smbcli_session_init(cli->transport, mem_ctx, false, session_options);
                if (session2 == NULL) {
                        d_printf("(%s) smbcli_session_init failed\n",
                                 __location__);
index 4fbffee41ed830bb591f17a8f78e699377dd1282..b7028e660959d5e74d46ea0fa6db585ab742c206 100644 (file)
@@ -53,7 +53,9 @@ struct samlogon_state {
        const char *comment;
        const char *account_name;
        const char *account_domain;
+       const char *netbios_name;
        const char *password;
+       const char *workgroup;
        struct dcerpc_pipe *p;
        int function_level;
        uint32_t parameter_control;
@@ -593,7 +595,7 @@ static bool test_lmv2_ntlmv2_broken(struct samlogon_state *samlogon_state,
        DATA_BLOB lmv2_response = data_blob(NULL, 0);
        DATA_BLOB lmv2_session_key = data_blob(NULL, 0);
        DATA_BLOB ntlmv2_session_key = data_blob(NULL, 0);
-       DATA_BLOB names_blob = NTLMv2_generate_names_blob(samlogon_state->mem_ctx, samlogon_state->iconv_convenience, TEST_MACHINE_NAME, lp_workgroup(global_loadparm));
+       DATA_BLOB names_blob = NTLMv2_generate_names_blob(samlogon_state->mem_ctx, samlogon_state->iconv_convenience, TEST_MACHINE_NAME, samlogon_state->workgroup);
 
        uint8_t lm_session_key[8];
        uint8_t user_session_key[16];
@@ -741,7 +743,7 @@ static bool test_lmv2_ntlm_broken(struct samlogon_state *samlogon_state,
        DATA_BLOB lmv2_response = data_blob(NULL, 0);
        DATA_BLOB lmv2_session_key = data_blob(NULL, 0);
        DATA_BLOB ntlmv2_session_key = data_blob(NULL, 0);
-       DATA_BLOB names_blob = NTLMv2_generate_names_blob(samlogon_state->mem_ctx, samlogon_state->iconv_convenience, lp_netbios_name(global_loadparm), lp_workgroup(global_loadparm));
+       DATA_BLOB names_blob = NTLMv2_generate_names_blob(samlogon_state->mem_ctx, samlogon_state->iconv_convenience, samlogon_state->netbios_name, samlogon_state->workgroup);
 
        DATA_BLOB ntlm_response = data_blob_talloc(samlogon_state->mem_ctx, NULL, 24);
        DATA_BLOB ntlm_session_key = data_blob_talloc(samlogon_state->mem_ctx, NULL, 16);
@@ -1337,6 +1339,8 @@ static bool test_SamLogon(struct dcerpc_pipe *p, TALLOC_CTX *mem_ctx,
        samlogon_state.account_name = account_name;
        samlogon_state.account_domain = account_domain;
        samlogon_state.password = plain_pass;
+       samlogon_state.workgroup = lp_workgroup(tctx->lp_ctx);
+       samlogon_state.netbios_name = lp_netbios_name(tctx->lp_ctx);
        samlogon_state.p = p;
        samlogon_state.creds = creds;
        samlogon_state.expected_error = expected_error;
index 21542e9b165f28099b10c45d214550957f8f02cf..3408a1924cfe82e18868bb9921084c86a0851815 100644 (file)
@@ -472,6 +472,7 @@ static NTSTATUS torture_leave_ads_domain(struct torture_context *torture,
        }
 
        ldb_set_opaque(ldb_ctx, "credentials", cmdline_credentials);
+       ldb_set_opaque(ldb_ctx, "loadparm", cmdline_lp_ctx);
 
        rtn = ldb_connect(ldb_ctx, remote_ldb_url, 0, NULL);
        if (rtn != 0) {
index 4d1b4a7ed0d12ac9f11b528152fd12dcfd557a5e..124e24415193297d6cc8816891b23a63d9383734 100644 (file)
@@ -256,6 +256,13 @@ static bool test_create_gentest(struct torture_context *torture, struct smb2_tre
        status = smb2_getinfo_file(tree, tmp_ctx, &q);
        CHECK_STATUS(status, NT_STATUS_OK);
        CHECK_EQUAL(q.access_information.out.access_flags, io.in.desired_access);
+
+       io.in.file_attributes = 0;
+       io.in.desired_access  = 0;
+       io.in.query_maximal_access = false;
+       io.in.share_access = 0;
+       status = smb2_create(tree, tmp_ctx, &io);
+       CHECK_STATUS(status, NT_STATUS_ACCESS_DENIED);
        
        talloc_free(tmp_ctx);
 
index d7482ddcf1f5e98b035435dedce835ce2b098da1..3bddde2a97ce5a78565e6f3f559d1c14cb77acdd 100644 (file)
@@ -56,15 +56,17 @@ static struct smbcli_state *connect_to_server(struct torture_context *tctx)
        const char *host = torture_setting_string(tctx, "host", NULL);
        const char *share = torture_setting_string(tctx, "share", NULL);
        struct smbcli_options options;
+       struct smbcli_session_options session_options;
 
        lp_smbcli_options(tctx->lp_ctx, &options);
+       lp_smbcli_session_options(tctx->lp_ctx, &session_options);
 
        status = smbcli_full_connection(tctx, &cli, host, 
                                        lp_smb_ports(tctx->lp_ctx),
                                        share, NULL,
                                        cmdline_credentials, 
                                        lp_resolve_context(tctx->lp_ctx),
-                                       tctx->ev, &options);
+                                       tctx->ev, &options, &session_options);
 
        if (!NT_STATUS_IS_OK(status)) {
                printf("failed to connect to //%s/%s: %s\n",
index 39d0a12ab1f640cfc9ab5d7919c9d722bc3789b0..d742e23e829de59e1f1ea09e13edb466b6d8874c 100644 (file)
@@ -77,14 +77,16 @@ static struct smbcli_state *connect_to_server(struct torture_context *tctx,
        const char *host = torture_setting_string(tctx, "host", NULL);
        const char *share = torture_setting_string(tctx, "share", NULL);
        struct smbcli_options options;
+       struct smbcli_session_options session_options;
 
        lp_smbcli_options(tctx->lp_ctx, &options);
+       lp_smbcli_session_options(tctx->lp_ctx, &session_options);
 
        status = smbcli_full_connection(tctx, &cli, host, 
                                        lp_smb_ports(tctx->lp_ctx),
                                        share, NULL,
                                        creds, lp_resolve_context(tctx->lp_ctx),
-                                       tctx->ev, &options);
+                                       tctx->ev, &options, &session_options);
 
        if (!NT_STATUS_IS_OK(status)) {
                printf("failed to connect to //%s/%s: %s\n",
index 938e7d6c038f9b9af6a6fadd32fdd7990edaa7c0..32e4453acad9ce81f3c9688587df8dad92299efd 100644 (file)
@@ -475,8 +475,10 @@ _PUBLIC_ bool torture_open_connection_share(TALLOC_CTX *mem_ctx,
        NTSTATUS status;
 
        struct smbcli_options options;
+       struct smbcli_session_options session_options;
 
        lp_smbcli_options(tctx->lp_ctx, &options);
+       lp_smbcli_session_options(tctx->lp_ctx, &session_options);
 
        options.use_oplocks = torture_setting_bool(tctx, "use_oplocks", true);
        options.use_level2_oplocks = torture_setting_bool(tctx, "use_level2_oplocks", true);
@@ -486,7 +488,7 @@ _PUBLIC_ bool torture_open_connection_share(TALLOC_CTX *mem_ctx,
                                        sharename, NULL,
                                        cmdline_credentials, 
                                        lp_resolve_context(tctx->lp_ctx),
-                                       ev, &options);
+                                       ev, &options, &session_options);
        if (!NT_STATUS_IS_OK(status)) {
                printf("Failed to open connection - %s\n", nt_errstr(status));
                return false;
index 3c2ffe7a00c188231a7e1e4406b823515c0d0a94..c579112b45ddf0c50580632de9c2935f6e735bf9 100644 (file)
@@ -221,7 +221,6 @@ static struct schema_conv process_convert(struct ldb_context *ldb, enum dsdb_sch
 
        for (attribute=schema->attributes; attribute; attribute = attribute->next) {
                const char *name = attribute->lDAPDisplayName;
-               const char *description = attribute->adminDescription;
                const char *oid = attribute->attributeID_oid;
                const char *syntax = attribute->attributeSyntax_oid;
                const char *equality = NULL, *substring = NULL;
@@ -270,7 +269,16 @@ static struct schema_conv process_convert(struct ldb_context *ldb, enum dsdb_sch
                        }
                }
                
-               schema_entry = schema_attribute_description(mem_ctx, target, seperator, oid, name, description, equality, substring, syntax, single_value, false);
+               schema_entry = schema_attribute_description(mem_ctx, 
+                                                           target, 
+                                                           seperator, 
+                                                           oid, 
+                                                           name, 
+                                                           equality, 
+                                                           substring, 
+                                                           syntax, 
+                                                           single_value, 
+                                                           false);
 
                if (schema_entry == NULL) {
                        ret.failures++;
@@ -291,7 +299,6 @@ static struct schema_conv process_convert(struct ldb_context *ldb, enum dsdb_sch
        /* This is already sorted to have 'top' and similar classes first */
        for (objectclass=schema->classes; objectclass; objectclass = objectclass->next) {
                const char *name = objectclass->lDAPDisplayName;
-               const char *description = objectclass->adminDescription;
                const char *oid = objectclass->governsID_oid;
                const char *subClassOf = objectclass->subClassOf;
                int objectClassCategory = objectclass->objectClassCategory;
@@ -356,7 +363,6 @@ static struct schema_conv process_convert(struct ldb_context *ldb, enum dsdb_sch
                                                        oid, 
                                                        name,
                                                        NULL, 
-                                                       description,
                                                        subClassOf,
                                                        objectClassCategory,
                                                        must,
index 37a19077f1eb31c47e6b70a9762b9c8de50c2953..0b98dcfa855de942587c486ecba2858d229812d3 100644 (file)
@@ -61,23 +61,6 @@ PRIVATE_DEPENDENCIES =
 
 setnttoken_OBJ_FILES = $(utilssrcdir)/setnttoken.o
 
-#################################
-# Start BINARY nmblookup
-[BINARY::nmblookup]
-INSTALLDIR = BINDIR
-PRIVATE_DEPENDENCIES = \
-               LIBSAMBA-HOSTCONFIG \
-               LIBSAMBA-UTIL \
-               LIBCLI_NBT \
-               LIBPOPT \
-               POPT_SAMBA \
-               LIBNETIF \
-               LIBCLI_RESOLVE
-# End BINARY nmblookup
-#################################
-
-nmblookup_OBJ_FILES = $(utilssrcdir)/nmblookup.o
-
 #################################
 # Start BINARY testparm
 [BINARY::testparm]
diff --git a/source4/utils/man/ndrdump.1.xml b/source4/utils/man/ndrdump.1.xml
deleted file mode 100644 (file)
index 9d66102..0000000
+++ /dev/null
@@ -1,83 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!DOCTYPE refentry PUBLIC "-//Samba-Team//DTD DocBook V4.2-Based Variant V1.0//EN" "http://www.samba.org/samba/DTD/samba-doc">
-<refentry id="ndrdump.1">
-
-<refmeta>
-       <refentrytitle>ndrdump</refentrytitle>
-       <manvolnum>1</manvolnum>
-</refmeta>
-
-
-<refnamediv>
-       <refname>ndrdump</refname>
-       <refpurpose>DCE/RPC Packet Parser and Dumper</refpurpose>
-</refnamediv>
-
-<refsynopsisdiv>
-       <cmdsynopsis>
-               <command>ndrdump</command>
-               <arg choice="opt">-c context</arg>
-               <arg choice="req">pipe</arg>
-               <arg choice="req">function</arg>
-               <arg choice="req">in|out</arg>
-               <arg choice="req">filename</arg>
-       </cmdsynopsis>
-       <cmdsynopsis>
-               <command>ndrdump</command>
-               <arg choice="opt">pipe</arg>
-       </cmdsynopsis>
-       <cmdsynopsis>
-               <command>ndrdump</command>
-       </cmdsynopsis>
-</refsynopsisdiv>
-
-<refsect1>
-       <title>DESCRIPTION</title>
-
-       <para>ndrdump tries to parse the specified <replaceable>filename</replaceable>
-               using Samba's parser for the specified pipe and function. The 
-               third argument should be 
-               either <emphasis>in</emphasis> or <emphasis>out</emphasis>, depending 
-               on whether the data should be parsed as a request or a reply.</para>
-
-       <para>Running ndrdump without arguments will list the pipes for which 
-               parsers are available.</para>
-
-       <para>Running ndrdump with one argument will list the functions that 
-               Samba can parse for the specified pipe.</para>
-
-       <para>The primary function of ndrdump is debugging Samba's internal 
-               DCE/RPC parsing functions. The file being parsed is usually 
-               one exported by wiresharks <quote>Export selected packet bytes</quote> 
-               function.</para>
-
-       <para>The context argument can be used to load context data from the request 
-               packet when parsing reply packets (such as array lengths).</para>
-
-</refsect1>
-
-<refsect1>
-       <title>VERSION</title>
-
-       <para>This man page is correct for version 4.0 of the Samba suite.</para>
-</refsect1>
-
-<refsect1>
-       <title>SEE ALSO</title>
-
-       <para>wireshark, pidl</para>
-
-</refsect1>
-
-<refsect1>
-       <title>AUTHOR</title>
-
-       <para>This utility is part of the <ulink url="http://www.samba.org/">Samba</ulink> suite, which is developed by the global <ulink url="http://www.samba.org/samba/team/">Samba Team</ulink>.</para>
-
-       <para>ndrdump was written by Andrew Tridgell. </para>
-
-       <para>This manpage was written by Jelmer Vernooij. </para>
-       
-</refsect1>
-
-</refentry>
index 8e1af99719178cf7bf2c32ddc2a9a5d557fd82a6..5209abeb2c2b04a7d744df5ef2a84acc3710c0e8 100755 (executable)
@@ -117,5 +117,92 @@ echo "Search Options Control Query test returned 0 items"
 failed=`expr $failed + 1`
 fi
 
+wellknown_object_test() {
+       local guid=$1
+       local object=$2
+       local basedns
+       local dn
+       local r
+       local c
+       local n
+       local failed=0
+
+       basedns="<WKGUID=${guid},${BASEDN}> <wkGuId=${guid},${BASEDN}>"
+       for dn in ${basedns}; do
+               echo "Test ${dn} => ${object}"
+               r=`bin/ldbsearch $options $CONFIGURATION -H $p://$SERVER '(objectClass=*)' -b "${dn}" | grep 'dn: '`
+               n=`echo "${r}" | grep 'dn: ' | wc -l`
+               c=`echo "${r}" | grep "${object}" | wc -l`
+
+               if [ $n -lt 1 ]; then
+                       echo "Object not found by WKGUID"
+                       failed=`expr $failed + 1`
+                       continue
+               fi
+               if [ $c -lt 1 ]; then
+                       echo "Wrong object found by WKGUID: [${r}]"
+                       failed=`expr $failed + 1`
+                       continue
+               fi
+       done
+
+       return $failed
+}
+
+wellknown_object_test 22B70C67D56E4EFB91E9300FCA3DC1AA ForeignSecurityPrincipals
+st=$?
+if [ x"$st" != x"0" ]; then
+       failed=`expr $failed + $st`
+fi
+wellknown_object_test 2FBAC1870ADE11D297C400C04FD8D5CD Infrastructure
+st=$?
+if [ x"$st" != x"0" ]; then
+       failed=`expr $failed + $st`
+fi
+wellknown_object_test AB1D30F3768811D1ADED00C04FD8D5CD System
+st=$?
+if [ x"$st" != x"0" ]; then
+       failed=`expr $failed + $st`
+fi
+wellknown_object_test A361B2FFFFD211D1AA4B00C04FD7D83A Domain Controllers
+st=$?
+if [ x"$st" != x"0" ]; then
+       failed=`expr $failed + $st`
+fi
+wellknown_object_test AA312825768811D1ADED00C04FD8D5CD Computers
+st=$?
+if [ x"$st" != x"0" ]; then
+       failed=`expr $failed + $st`
+fi
+wellknown_object_test A9D1CA15768811D1ADED00C04FD8D5CD Users
+st=$?
+if [ x"$st" != x"0" ]; then
+       failed=`expr $failed + $st`
+fi
+
+echo "Getting HEX GUID/SID of $BASEDN"
+HEXDN=`bin/ldbsearch $CONFIGURATION $options -b "$BASEDN" -H $p://$SERVER -s base "(objectClass=*)" --controls=extended_dn:1:0 | grep 'dn: ' | cut -d ' ' -f2-`
+HEXGUID=`echo "$HEXDN" | cut -d ';' -f1`
+HEXSID=`echo "$HEXDN" | cut -d ';' -f2`
+echo "HEXGUID[$HEXGUID]"
+echo "HEXSID[$HEXSID]"
+
+echo "Getting STR GUID/SID of $BASEDN"
+STRDN=`bin/ldbsearch $CONFIGURATION $options -b "$BASEDN" -H $p://$SERVER -s base "(objectClass=*)" --controls=extended_dn:1:1 | grep 'dn: ' | cut -d ' ' -f2-`
+echo "STRDN: $STRDN"
+STRGUID=`echo "$STRDN" | cut -d ';' -f1`
+STRSID=`echo "$STRDN" | cut -d ';' -f2`
+echo "STRGUID[$STRGUID]"
+echo "STRSID[$STRSID]"
+
+SPECIALDNS="$HEXGUID $HEXSID $STRGUID $STRSID"
+for SPDN in $SPECIALDNS; do
+       echo "Search for $SPDN"
+       nentries=`bin/ldbsearch $options $CONFIGURATION -H $p://$SERVER -s base -b "$SPDN" '(objectClass=*)' | grep "dn: $BASEDN"  | wc -l`
+       if [ $nentries -lt 1 ]; then
+               echo "Special search returned 0 items"
+               failed=`expr $failed + 1`
+       fi
+done
 
 exit $failed